ProgrammingHardCompetitive coding (CP)

How many pairs (i, j) with i < j have an even sum? Compute with this program.

How many pairs (i, j) with i < j have an even sum? Compute with this program.
#include <stdio.h>
int main(void) {
    int a[] = {1, 2, 3, 4, 5}, c = 0;
    for (int i = 0; i < 5; i++)
        for (int j = i + 1; j < 5; j++)
            if ((a[i] + a[j]) % 2 == 0) c++;
    printf("%d", c);
}
  1. A. 6
  2. B. 3
  3. C. 4
  4. D. 5

Correct answer: C. 4

Two numbers sum to an even value when both are odd or both are even. The odd values 1, 3, 5 give 3 pairs and the even values 2, 4 give 1 pair, for 4 in total.

More C Programming questions

Exams that ask this topic