ProgrammingHardTCS NQT · Accenture

How many pairs (i, j) with i < j have a[i] == a[j]? Compute with this program.

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

Correct answer: C. 3

The equal pairs are (0,3), (1,4) and (2,5), so the count is 3. Each value occurs exactly twice, so no value gives more than one pair.

More C Programming questions

Exams that ask this topic