C++

Finding The Second-Largest Entry In An Array Using C++

The second-largest element in an array is located using this program. The number of elements the user wishes to enter is indicated by the software by asking for the value of n. The array’s elements must be entered by the user. The for loop is then used to locate the array’s second-largest element.

You should have a basic understanding of C++ loops, if-else statements, and C++ arrays in order to comprehend this program.

Program to locate the second-largest member in an array of n elements, for instance

#include <iostream>
using namespace std;
int main(){
   int n, num[50], largest, second;
   cout<<"Enter number of elements: ";
   cin>>n;
   for(int i=0; i<n; i++){
      cout<<"Enter Array Element"<<(i+1)<<": ";
      cin>>num[i];
   }
   /* Here we are comparing first two elements of the
    * array, and storing the largest one in the variable
    * "largest" and the other one to "second" variable.
    */
   if(num[0]<num[1]){ 
      largest = num[1];
      second = num[0];
   }
   else{ 
      largest = num[0];
      second = num[1];
   }
   for (int i = 2; i< n ; i ++) {
      /* If the current array element is greater than largest
       * then the largest is copied to "second" and the element
       * is copied to the "largest" variable.
       */
      if (num[i] > largest) {
         second = largest;
         largest = num[i];
      }
      /* If current array element is less than largest but greater
       * then second largest ("second" variable) then copy the
       * element to "second"
       */
      else if (num[i] > second && num[i] != largest) {
         second = num[i];
      }
   }
   cout<<"Second Largest Element in array is: "<<second;
   return 0;
}

Output:

Enter number of elements: 5
Enter Array Element1: 12
Enter Array Element2: 31
Enter Array Element3: 9
Enter Array Element4: 21
Enter Array Element5: 3
Second Largest Element in array is: 21

Explanation:

If the user enters 5 for the value of n, the first for loop has run five times, storing the first element in num[0], the second in num[1], and so on, in the array.

Following the first for loop, an if-else clause compares the array’s first two members and puts the larger one in the “biggest” variable and the smaller one in the “second” variable. The “biggest” and “second” variables in this program denote the largest and second-largest elements, respectively.

If there is an element greater than largest, it is copied to largest in the second loop, which analyzes the remaining array elements and compares them one by one with the largest variable.

The second for loop has an else if clause that determines if there is any element that is the largest but not the second before updating the second variable.

Related Articles

Leave a Reply

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

Back to top button