C++ Program to Find Largest Element of an Array


An array contains multiple elements and the largest element in an array is the one that is greater than other elements.

For example.

51724

In the above array, 7 is the largest element and it is at index 2.

A program to find the largest element of an array is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a[] = {4, 9, 1, 3, 8};
   int largest, i, pos;
   largest = a[0];
   for(i=1; i<5; i++) {
      if(a[i]>largest) {
         largest = a[i];
         pos = i;
      }
   }
   cout<<"The largest element in the array is "<<largest<<" and it is at index "<<pos;
   return 0;
}

Output

The largest element in the array is 9 and it is at index 1

In the above program, a[] is the array that contains 5 elements. The variable largest will store the largest element of the array.

Initially largest stores the first element of the array. Then a for loop is started which runs from the index 1 to n. For each iteration of the loop, the value of largest is compared with a[i]. If a[i] is greater than largest, then that value is stored in largest. And the corresponding value of i is stored in pos.

This is demonstrated by the following code snippet.

for(i=1; i<5; i++) {
   if(a[i]>largest) {
      largest = a[i];
      pos = i;
   }
}

After this, the value of the largest element in the array and its position is printed.

This is shown as follows −

cout<<"The largest element in the array is "<<largest<<" and it is at index "<<pos;

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 12-Feb-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements