Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find the second largest number of an array

C++ Code Example — Array Programs

ADVERTISEMENT

WAP to find the second largest number of an array

Objective

Write a C++ program to find the second largest element of an array.

Algorithm / Approach

  1. Find the absolute largest element (max) and record its index m.
  2. Initialize the second largest smax to a different element.
  3. Loop through the array again, skipping index m.
  4. If you find a number larger than smax, update it: if(smax < a[i] && m != i).
  5. Print the second largest element.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int m = 0, a[5],max,smax ;
 cout<<"Enter 5 Elements : ";
 for(int i =0; i< 5; i++) {
  cin>>a[i];
 }
 max = a[0];
 for(int i =1; i< 5; i++) {
  if(a[i]>max) {
   max = a[i];
   m = i;
  }
  }
 smax = a[5-m-1];
 for(int i =0 ; i< 5; i++) {
  if(smax< a[i] && m!= i) {
   smax = a[i];
  }
 }
 cout<<"Second Max = "<< smax;
return 0;
}

Expected Output

Enter 5 Elements : 1 3 45 32 54
Second Max = 45

Explanation of the Program

  • Just like finding the second smallest, we identify the champion and then find the best of the remaining contenders by explicitly ignoring the champion's index.
  • An alternative approach would be to sort the entire array in descending order and simply pick the second element, but sorting takes O(n log n) time, making this two-pass O(n) approach mathematically faster.

Complexity

Time Complexity O(n)
Space Complexity O(n)
ADVERTISEMENT