This program finds the second largest element in an array. The program asks the user to enter the value of n, which is the number of elements user wish to enter. The user is asked to enter the elements of array. The program then finds the second largest element of the array using for loop.
To understand this program, you should have the basic knowledge of C++ loops, if-else statement and C++ arrays.
Example: Program to find the second largest element in an array of n elements
#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:
User enters 5 as the value of n, which means the first for loop ran times to store the each element entered by user to the array, first element in num[0], second in num[1] and so on.
After first for loop, there is a if-else statement which compares the first two elements of array and stores the greater one in “largest” variable and smaller one in “second”. Note: In this program the “largest” variable is for the largest element and “second” is for second largest.
Second loop checks the remaining elements of array and compares them one by one with the largest variable to see if there is any element greater than largest, if there is any then the element is copied to largest.
There is an else if part in the second for loop which checks whether there is any element< largest but > than second, then it updates the second variable.
Leave a Reply