#include <stdio.h>
enum { SIZE = 10 };
int main() {
int A[SIZE];
for (int i = 0; i < SIZE; i++) {
scanf("%d", &A[i]);
}
int max_1 = A[0];
int max_2 = A[1];
for (int i = 0; i < SIZE; i++) {
if (A[i] > max_1) {
max_2 = max_1;
max_1 = A[i];
}
}
for (int i = 0; i < SIZE; i++) {
if (A[i] > max_2 && A[i] != max_1) {
max_2 = A[i];
}
}
int sum = max_1 + max_2;
printf("%d", sum);
return 0;
}
This code reads 10 integers into an array, then attempts to find the two largest distinct values and print their sum. The logic has a flaw in how it initializes and updates the two maximum values.
- The initial values `max_1 = A[0]` and `max_2 = A[1]` assume the first two elements are the largest, but if `A[0]` is the largest overall, `max_2` might start with a value that is not actually the second largest. Consider what happens if the largest value appears at index 0 and the second largest appears later.
- The first loop that updates `max_1` and `max_2` only updates `max_2` when a new `max_1` is found. It does not handle the case where `A[i]` is between `max_2` and `max_1` (i.e., greater than `max_2` but less than `max_1`). The second loop tries to fix this, but the initial incorrect `max_2` can still cause problems.