Largest Element in an array using C++

Find Largest element in an array using C++

In this program we will find the maximum element of the array using iterative approach. We will initialize the starting element of array as largest one and compare with all other elements of the given array and update the largest value.

Sample Test Case :

Enter size of array : 5
Enter elements of array : 52 24 12 36 95
Output
Largest element in array : 95

Finding Largest Element in an Array using C++

Algorithm

  1. Start.
  2. Declare an array of given size.
  3. Initialize largest element to arr[0].
  4. Traverse the entire array using for loop.
  5. If arr[i] > largest, update largest to arr[i].
  6. Once we reach the end of loop, display the current value of largest.
  7. End.

C++ Code

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int size;
    
    cout << “Enter size of array : “ << endl;
    
    cin >> size;
    int arr[size];
    
    cout << “Enter elements of array : “ << endl;
    
    for(int i=0i<sizei++)
    {
        cin >> arr[i];
    }
    
    int largest = arr[0];   // initialize largest to arr[0]
    
    for(int i=1i<sizei++)  
    {
        if(arr[i]>largest)   // compare current element with largest
        {
            largest = arr[i];
        }
    }
    
    cout << “Largest Element in the array : “ << endl << largest;  // display result

    return 0;
}


Output

Enter size of array :                                                                                                                          
5    

Enter elements of array :                                                                                                                      
52 24 12 36 95  
                                                                                                                               
Largest Element in the array :                                                                                                                 
95 
 

This page is contributed by Rishav Raj.