C++ Program to Find Largest Element in an Array
In this article, we will learn to write a C++ program to find the largest element in the given array arr of size N. The element that is greater than all other elements is the largest element in the array.
One of the most simplest and basic approaches to find the greatest element in an array is to simply traverse the whole list and maintain a variable max to store the maximum element so far and compare this max element with the current element and update the max if any element greater than max is encountered.
Algorithm
- Create a local variable max to store the maximum among the list.
- Initialize max with the first element initially, to start the comparison.
- Then traverse the given array from the second element till the end, and for each element:
- Compare the current element with the max
- If the current element is greater than max, then replace the value of max with the current element.
- In the end, return and print the value of the largest element of the array stored in max.
C++ Program to Find Largest Number in an Array
C++
#include <bits/stdc++.h>
using namespace std;
int largest( int arr[], int n)
{
int i;
int max = arr[0];
for (i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
int main()
{
int arr[] = { 10, 324, 45, 90, 9808 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Largest in given array is " << largest(arr, n);
return 0;
}
|
Output
Largest in given array is 9808
Complexity Analysis
- Time complexity: O(N), to traverse the Array completely.
- Auxiliary Space: O(1), as only an extra variable is created, which will take O(1) space.
Refer to the complete article Program to find largest element in an Array for optimized methods to find the largest element in an array.
Last Updated :
03 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...