find second highest number in c++

To find the second highest number in C++, you can follow these steps:

  1. Initialize two variables, max and secondMax, with the minimum possible value for the data type you are working with. For example, if you are working with integers, you can set max and secondMax to the smallest possible integer value (INT_MIN).

  2. Iterate through the array or list of numbers to find the maximum number. Compare each number with the current value of max. If the number is greater than max, update both max and secondMax. If the number is only greater than secondMax, update only secondMax.

  3. After the iteration, the value of secondMax will be the second highest number in the array.

Here's an example code snippet in C++ that implements these steps:

#include <iostream>
#include <climits>

int main() {
    int numbers[] = {5, 10, 3, 8, 1};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    int max = INT_MIN;
    int secondMax = INT_MIN;

    for (int i = 0; i < size; i++) {
        if (numbers[i] > max) {
            secondMax = max;
            max = numbers[i];
        } else if (numbers[i] > secondMax && numbers[i] != max) {
            secondMax = numbers[i];
        }
    }

    std::cout << "The second highest number is: " << secondMax << std::endl;

    return 0;
}

In this example, we have an array of numbers {5, 10, 3, 8, 1}. We initialize max and secondMax with INT_MIN. Then, we iterate through each number in the array. If a number is greater than max, we update both max and secondMax. If a number is only greater than secondMax, we update only secondMax. After the iteration, secondMax will hold the second highest number in the array, which in this case is 8. Finally, we print the value of secondMax to the console.