Python program that uses a for loop and an initial maximum value to print the largest element in an array:
def largest_element(arr):
max_val = arr[0]
for i in arr:
if i > max_val:
max_val = i
return max_val
# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(largest_element(arr))
The function largest_element(arr)
takes an array as an argument. It uses a for loop to iterate over the elements of the array. The function declares a variable max_val
and assigns the value of the first element of the array to it. Then, it compares each element of the array with the max_val
and if the element is greater than max_val
, it assigns the element value to max_val
. Finally, it returns the max_val
as the largest element in the array.
The example usage creates an array and calls the largest_element()
function to find the largest element in the array, and then it prints the largest element.
You could also use the max()
function to find the largest element in an array, this method is more pythonic and efficient.
def largest_element(arr):
return max(arr)
This method uses the max()
function