This is a C++ program that finds the second largest element in an array of integers. The program first asks the user to enter the number of elements they want to enter into the array. It then uses a for loop to prompt the user to enter each element one by one and stores them in the num array.
After filling up the array, the program initializes two variables largest and second to the first and second elements of the array respectively. It then loops through the remaining elements of the array using another for loop and compares each element with the current values of largest and second. If the element is greater than largest, the program updates the values of largest and second accordingly.
If the element is not greater than largest but greater than second, the program updates the value of second to that element. Finally, the program outputs the value of second as the second largest element in the array.
#include <iostream> using namespace std; int main() { int n,num[50],largest,second; cout<<"\nEnter number of elements: "; cin>>n; for(int i=0;i<n;i++) { cout<<"\nEnter Array Element"<<(i+1)<<": "; cin>>num[i]; } 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(num[i]>largest) { second=largest; largest=num[i]; } else if(num[i]>second && num[i]!=largest) { second=num[i]; } } cout<<"\nSecond Largest Element in array is: "<<second; return 0; }To download raw file Click Here
Enter number of elements you want to enter: 5 Enter Element 1: 11 Enter Element 2: 12 Enter Element 3: 13 Enter Element 4: 14 Enter Element 5: 15 Second Largest Element in array is: 14
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions