Find Second Largest Number using Array in C++


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.

Source Code

#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

Output

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

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples