C++ Program to Find Largest Element in an Array

In this post, you will learn how to Find Largest Element in an Array using C++ programming language.

This lesson will teach you how to Find Largest Element in an Array, using assignment operators, decision making statement and the for loop statement using the C++ Language. Let’s look at the below source code.

How to Find Largest Element in an Array?

RUN CODE SNIPPET

Source Code

#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

The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code.

Now we can look into the working and layout of the code’s function.

  1. Initialize the variable as an array “[ ]”  which holds the integer values and assign the values to a.
  2. Initialize the string values largest, i, pos as integers and assign the variable largest = a[0]
  3. Declare the for loop with the condition (i=1; i<5; i++) and in the body of the loop declare an if statement with the condition (a[i]>largest).
  4. In the loop statement using the assignment operator perform the following operations.
    { largest = a[i]; pos = i; }
  5. Using the output function cout display the output statements with the integer which holds the answer, and end the source with a return function.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this post, you will learn how to Check Armstrong Number using C++ programming language. This lesson will teach you...
  • C++
  • December 2, 2024
In this post, you will learn how to Calculate the Sum of Natural Numbers using C++. This lesson will teach...
  • C++
  • December 2, 2024
In this post, you’ll learn how to write a Program to Add Two Integers in C++. This lesson will help...
  • C++
  • November 30, 2024