Python Program to find smallest element of array


April 3, 2022, Learn eTutorial
1366

In this simple python program, we have to find the smallest element of the array. It's an intermediate-level python program.

To understand this example, you should have knowledge of the following Python programming topics:

How to get the smallest element of an array?

In this simple python program based on arrays, to find the smallest of the elements of the array. An array is a set of elements of the same data type. an Array can be accessed by a common variable. To find the smallest element of the array, we are assigning the first element of the array to a variable and we open a  for loop to traverse to the end of the array.

In every iteration, we compare the first element stored in a variable with each array element using an if condition in python. If the array element is less than the variable then the variable value is swapped to the smallest. Finally, we get the smallest element in the variable.

For example, consider a simple 2D array in python language. array = [3, 2, 1, 4, 5]. We give the first value 3 in a variable A and compare that variable A with each element in the array using a for loop. let us take the second element in the array which is 2. so it is less than the variable value 3. So Variable changes to 2. Like that we get the lowest value in the variable when the loop is fully iterated and we print the variable using python syntax and python methods.

ALGORITHM

STEP 1: Initialize an array with some predefined values.

STEP 2: Assign the first element in the array to a variable.

STEP 3: Use a for loop to travel to the end of the array from the first element.

STEP 4: Use an if condition to compare the value of array elements with the variable.

STEP 5: Assign the variable with the lower value of the array element if the array element is less than the variable value.

STEP 6: Print the smallest value from the variable using print in the python programming language. We use the str() function in python programming to convert the integer variable to string.

Python Source Code

                                          arr = [3, 2, 1, 4, 5];     
        
min = arr[0];  #Assign the first element 
     
for i in range(0, len(arr)): # loop for traversing through the array

   if(arr[i] < min):  # use if condition to compare 
  
       min = arr[i];    
     
print("Smallest element in array is: " + str(min)); 
                                      

OUTPUT

Smallest element in array is: 1