Open In App

C++ Program to Find Largest Element in an Array

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Largest-element-in-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++




// C++ program to find maximum
// in arr[] of size n
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the largest
// number in array
int largest(int arr[], int n)
{
    int i;
  
    // Initialize maximum element
    int max = arr[0];
  
    // Traverse array elements
    // from second 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[] = { 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
Previous
Next
Share your thoughts in the comments
Similar Reads