Example HTML page

A Python program to find the highest and lowest elements in an array

We already know that an array is data structure where we can store the values of similar data type. In Python there is possibility of using lists instead of arrays. In this post I will show you how to write a python program to find the highest and lowest elements in an array.

#To find highest element in an array

def highest(arr,n):
     high = arr[0]
     for i in range(1, n): 
        if arr[i] > high: 
            high = arr[i] 
     return high
arr = [12,34,256,265,154,1.2] 
n = len(arr) 
res = highest(arr,n) 
print ("Highest element in array is: ",res)

Output

Highest element in array is:  265

 Explanation

Firstly we defined a function called “highest” and also we passed parameters ‘arr’ and ‘n’ in to it. Next we are initializing an array ‘arr’ and is stored in variable ‘high’. By using for loop we perform traversing on every element in an array. Here every element in the array is compared with current highest element and then returns the highest element among those compared.This procedure continues until the base condition  ‘if arr[i] > high’ becomes true. Now the list of elements is appended to an array and is stored in a variable ‘arr’. The ‘len( )’ method evaluates the length of an array and is allocated to variable ‘n’. The function definition ‘res = highest(arr,n)’ is called and finally prints the output.

Similarly we can also write a python program to find the lowest element  in an array. It is shown in below code.

# To find lowest element in an array

def lowest(arr,n):
     low = arr[0]
     for i in range(1, n): 
        if arr[i] < low: 
            low = arr[i] 
     return low
arr = [17,24,46,3.33,23.9,123] 
n = len(arr) 
res = lowest(arr,n) 
print ("Lowest element in array is: ",res)   

Output

Lowest element in array is:  3.33

 

Example HTML page

Leave a Reply

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

Pin It on Pinterest