Find The Largest Element In An Array Using C++ – Q&A

This software locates the greatest array element. The application first asks the user to input n, the number of elements in the array, before asking for the array’s elements. Next, the software displays the element that is the largest.

You should know the fundamentals of loops, arrays, and C++ if-else statements in order to comprehend this program.

Using an array of n elements, a program to determine the largest element

#include <iostream>
using namespace std;
int main(){
   //n is the number of elements in the array
   int n, largest;
   int num[50];
   cout<<"Enter number of elements you want to enter: ";
   /* Loop runs from o to n, in such a way that first
    * element entered by user is stored in num[0], second 
    * in num[1] and so on. 
   for(int i = 0; i < n; i++) {
      cout<<"Enter Element "<<(i+1)<< ": ";
   // Storing first array element in "largest" variable
   largest = num[0];
   for(int i = 1;i < n; i++) {
      /* We are comparing largest variable with every element
       * of array. If there is an element which is greater than
       * largest variable value then we are copying that variable
       * to largest, this way we have the largest element copied
       * to the variable named "largest" at the end of the loop 
      if(largest < num[i])
         largest = num[i];
   cout<<"Largest element in array is: "<<largest;
   return 0;


Enter number of elements you want to enter: 5
Enter Element 1: 19
Enter Element 2: 21
Enter Element 3: 3
Enter Element 4: 89
Enter Element 5: 13
Largest element in array is: 89


When the user enters 5, the loop that saves the input values into the array executes five times, storing the first entered value in num[0], the second in num[1], and so on.

The integer variable “biggest,” which is assigned to the first element, had a value of 19 before to the commencement of the second loop.

In the first iteration of the second loop, the value of the largest variable, 19, is compared to 21, and since 21 is greater than 19, the “if” condition is satisfied, and the largest variable’s value is changed to 21.

In the second iteration of the loop, the greatest value, 21, is compared to 3, but since three is less than 21, the “if” condition is false and nothing happens.

The “biggest” variable is given the value of 89 in the third iteration of the loop if the condition that 89 is greater than 21 is true.

Fourth iteration of loop: Nothing happens because 13 is a little number when compared to 89 (value of largest variable).
Closed loop.

At the conclusion of the loop, the value in the “biggest” variable is 89, which we have shown as the solution.

Related Articles

Leave a Reply

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

Back to top button