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:
- Initialize maxVal = arr[0].
- Loop through the array for i -> 1 to n.
- if (arr[i] > maxVal), then maxVal = arr[i].
- Print maxVal.
Program to find the largest element in an array
Output:
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