How to find the maximum element in an array
An array stores data. The data can be of any type, and each element represents a specific piece of information.
Algorithm
Suppose there is a team of five players, ​and the oldest player is going to become the captain.
-
The array that stores the age of all the players will be traversed to find the maximum age.
-
A variable named (
max) that stores the maximum element found so far will be initialized. -
Initially, the first element will be set as the
maxand then the array will be traversed. -
Each element will be compared with the
max, and if the current element is greater than themax, themaxwill be set to the current element. -
Finally, the
maxis returned.
The following slides better explain this problem:
Code
The following codes find the outputs and maximum element in the array:
#include <iostream>using namespace std;int largest(int arr[], int n){int i;// Initialize maximum elementint max = arr[0];// Traverse array elements// and compare every element with current maxfor (i = 1; i < n; i++)if (arr[i] > max){max = arr[i];}return max;}// Driver Codeint main(){int arr[] = {18, 24, 21, 27, 19};// ages of playersint n = sizeof(arr) / sizeof(arr[0]);cout << "Maximum element is "<< largest(arr, n);return 0;}
Free Resources