find second highest number in c++
To find the second highest number in C++, you can follow these steps:
Initialize two variables,
max
andsecondMax
, with the minimum possible value for the data type you are working with. For example, if you are working with integers, you can setmax
andsecondMax
to the smallest possible integer value (INT_MIN
).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 thanmax
, update bothmax
andsecondMax
. If the number is only greater thansecondMax
, update onlysecondMax
.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.