Trusted answers to developer questions

How to find the maximum element in an array

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.

  1. The array that stores the age of all the players will be traversed to find the maximum age.

  2. A variable named (max) that stores the maximum element found so far will be initialized.

  3. Initially, the first element will be set as the max and then the array will be traversed.

  4. Each element will be compared with the max, and if the current element is greater than the max, the max will be set to the current element.

  5. Finally, the max is returned.

The following slides better explain this problem:

1 of 7

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 element
int max = arr[0];
// Traverse array elements
// and compare every element with current max
for (i = 1; i < n; i++)
if (arr[i] > max)
{
max = arr[i];
}
return max;
}
// Driver Code
int main()
{
int arr[] = {18, 24, 21, 27, 19};// ages of players
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum element is "
<< largest(arr, n);
return 0;
}

RELATED TAGS

how
find
maximum
element
array
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?