Find the second highest number in an integer array in C++

This program is able to find the second highest number in an integer array in C++ by using some suitable conditions. This is a question based on array and it utilizes conditional statements.

  • Array elements can be in any order.
  • The size of array n will be given by the user.

Programming approach

  • Declare an integer array with size defined by the user.
  • Store values of array entered by the user.
  • Find the required value i.e. the second highest number.
  • Print the number on the screen.

Program: Find the second highest number in an integer array in C++

Program/Source code

Following is the complete C++ program for the required problem statement. It is successfully compiled and tested working.

/* C++ program to find second highest number in array**


#include <iostream>
using namespace std;
int main()
{
    int size;
    cout<<"Enter the size of array: ";
    cin>>size;

    cout<<"Enter array elements: ";
    int array[size];                            // array declaration
    for(int i=0;i<size;i++)
        cin>>array[i];                          // input array values

    int highest=-2147483648;                    // minimum integer values
    int secondhigh=-2147483648;

    for(int i=0;i<size;i++){                    // logic for maximum and second maximum value
        if(highest<array[i]){
            secondhigh=highest;
            highest=array[i];
        }
        if(secondhigh<array[i]&& array[i]<highest)
            secondhigh=array[i];
    }
    
    cout<<endl;
    cout<<"The second highest number present in array is "<<secondhigh;
    return 0;
}

Output Example

Enter the size of array: 5
45
24
65
84
69
The number present int first array but not in second is 69
Process returned 0 (0x0) execution time : 14.390 s
Press any key to continue.

In the above example, the required value is found from an array of size 5.

Enter the size of array: 6
Enter array elements: 23
133
56
25
36
256

The second highest number present in array is 133
Process returned 0 (0x0)   execution time : 21.890 s
Press any key to continue.

Program Explanation

  • Declare an array with size that the user enters.
  • Store arrays values similarly.
  • Declare variables to store maximum and second maximum values of the array respectively.
  • Use a for loop which circulates through the array.
  • Use suitable conditions with if statement so that required values can be found.
  • Store the result in the declared variables and print it on the screen.

Also, read

How to remove or eliminate the extra spaces from a given string in C++

Leave a Reply

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