Q:

# Python program to find the largest element in an array

belongs to collection: Python Array Programs

Example: studentArray[] = {"John", "Prem", "Kiran", "Joe"}

In this program, we will take the array and its size as input from the user and print the largest value of the array.

Example:

```Input:
7
4	5	9	1	12	8	3

Output:
The largest element of the array is 12
```

To find the largest element of the array, we will initialize a maxVal variable with the first value of the array arr[0]. Then looping from 1 to n, we will compare maxVal with all values of the array. And if any value is greater than maxVal, we will replace maxVal with it. At last, we will print the maxVal.

Algorithm:

1. Initialize maxVal = arr[0].
2. Loop through the array for i -> 1 to n.
• if (arr[i] > maxVal), then maxVal = arr[i].
3. Print maxVal.

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to find the largest element in an array

``````# Python program to find the Largest element of the array

# function to find the Largest element of array
def FindLargestElement(arr,n):
maxVal = arr[0]

for i in range(1, n):
if arr[i] > maxVal:
maxVal = arr[i]
return maxVal

# code to take user input for the array...
n = int(input("Enter the number of elements in the array: "))
arr = []
print("Enter elements of the array: ")
for i in range(n):
numbers = int(input())
arr.append(numbers)

# Calling the method to find the largest value
maxVal = FindLargestElement(arr,n)
print ("Largest in given array is",maxVal)``````

Output:

```Enter the number of elements in the array: 5
Enter elements of the array:
10
12
45
10
5
Largest in given array is 45
```

Explanation:

In the above code, we have taken the array as input from the user and stored it in the variable arr. Then we have called a method named findLargestElement() which will compute the maximum value of the array and return it. This return value is stored in a maxVal variable and then printed.

findLargestElement() function: the function accepts the array and its size as input and returns the maximum value of the array.

The function initializes a variable maxVal with the first value of the array. Then loops through the array and if the value of arr[i] is greater than maxVal, puts the value of arr[i] to maxVal. After the loop ends the function returns the maxVal.

need an explanation for this answer? contact us directly to get an explanation for this answer