Python program to print the smallest element in an array

Created with Sketch.

Python program to print the smallest element in an array

In this program, we need to find out the smallest element present in the array. This can be achieved by maintaining a variable min which initially will hold the value of the first element. Loop through the array by comparing the value of min with elements of the array. If any of the element’s value is less than min, store the value of the element in the min.

 

Consider above array. Initially, min will hold the value 25. In the 1st iteration, min will be compared with 11. Since 11 is less than 25. Min will hold the value 11. In a 2nd iteration, 11 will be compared with 7. Now, 7 is less than 11. So, min will take the value 7. Continue this process until the end of the array is reached. At last, min will hold the smallest value element in the array.

ALGORITHM:

  • STEP 1: Declare and initialize an array.
  • STEP 2: Store first element in the variable min.
  • STEP 3: Loop through the array from 0 to length of the array and compare the value of min with elements of the array.
  • STEP 4: If any element is less than min, min will hold the value of that element.
  • STEP 5: At last, min will represent the smallest element in the array.

PROGRAM:

  1. #Initialize array   
  2. arr = [251177556];
  3. #Initialize min with the first element of the array.  
  4. min = arr[0];
  5. #Loop through the array  
  6. for i in range(0, len(arr)):
  7.     #Compare elements of array with min  
  8.    if(arr[i] < min):
  9.        min = arr[i];
  10. print(“Smallest element present in given array: “ + str(min));

Output:

Smallest element present in given array: 7

Leave a Reply

Your email address will not be published. Required fields are marked *