HomeC++C++ Program to Find Largest Element in an Array

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 Generate Multiplication Table using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Display Fibonacci Sequence using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Find GCD of two Numbers using C++ programming language. This lesson will...
  • C++
  • January 30, 2022