ProgrammingHardTCS NQT · Accenture

How many pairs (i, j) with i < j in {1, 3, 5, 8, 10} have a difference of exactly 2 (that is, a[j] - a[i] = 2)? Compute with this program.

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

Correct answer: D. 3

The pairs with difference 2 are (1, 3), (3, 5) and (8, 10), so the count is 3.

More C Programming questions

Exams that ask this topic