Find the Second Largest Value
Find the second distinct largest array value.
What is Find the Second Largest Value?
Tracking two best values avoids sorting the entire array.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <limits.h>
#include <stdio.h>
int main(void) {
int values[] = {7, 23, 12, 23, 9}, first = INT_MIN, second = INT_MIN;
// Maintain the two largest distinct values.
for (int i = 0; i < 5; ++i) { int value = values[i]; if (value > first) { second = first; first = value; } else if (value > second && value != first) second = value; }
printf("second=%d\n", second);
}
second=12
C++
main.cpp
#include <iostream>
#include <limits>
#include <vector>
int main() {
std::vector values{7, 23, 12, 23, 9}; int first = std::numeric_limits<int>::min(), second = first;
// Maintain the two largest distinct values.
for (int value : values) { if (value > first) { second = first; first = value; } else if (value > second && value != first) second = value; }
std::cout << "second=" << second << '\n';
}
second=12
C and C++ comparison
Update both positions when a new maximum appears and update only second when a value lies between them.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges