Friday, September 5, 2025
HomeData Modelling & AIC++ Program to Find Largest Element in an Array

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.

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.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS