Beginner C/C++ Exercises

Find the Second Largest Value

Tracking two best values avoids sorting the entire array.

What is Find the Second Largest Value?

Tracking two best values avoids sorting the entire array.

Find the second distinct largest array value.

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

C
Run code →
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);
}
Expected output
second=12
C++
Run code →
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';
}
Expected output
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.