find second largest number in array c++
To find the second largest number in an array in C++, you can follow these steps:
- Initialize two variables,
largest
andsecondLargest
, with the minimum possible value for integers (INT_MIN
). - Traverse the array and compare each element with the
largest
variable. - If the current element is greater than the
largest
variable, update bothlargest
andsecondLargest
variables accordingly. - If the current element is smaller than the
largest
variable but greater than thesecondLargest
variable, update only thesecondLargest
variable. - After traversing the entire array, the
secondLargest
variable will hold the second largest number.
Here is an example code snippet that demonstrates the above steps:
#include <iostream>
#include <climits>
int findSecondLargest(int arr[], int size) {
int largest = INT_MIN;
int secondLargest = INT_MIN;
for (int i = 0; i < size; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
int main() {
int arr[] = {5, 7, 2, 9, 1, 10};
int size = sizeof(arr) / sizeof(arr[0]);
int secondLargest = findSecondLargest(arr, size);
std::cout << "The second largest number is: " << secondLargest << std::endl;
return 0;
}
In this code, the findSecondLargest
function takes an array arr
and its size size
as parameters. It initializes the largest
and secondLargest
variables to the minimum possible integer value using the INT_MIN
constant from the <climits>
header.
The function then iterates over each element of the array using a for
loop. For each element, it compares it with the largest
variable. If the current element is greater than the largest
variable, it updates both the largest
and secondLargest
variables. If the current element is smaller than the largest
variable but greater than the secondLargest
variable, it updates only the secondLargest
variable.
Finally, the findSecondLargest
function returns the value of the secondLargest
variable.
In the main
function, we create an example array arr
and calculate its size using the sizeof
operator. We then call the findSecondLargest
function with the array and its size, and store the result in the secondLargest
variable. Finally, we print the value of the secondLargest
variable to the console.