ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
#include <stdio.h>
int main(void) {
    int a[] = {1, 2, 3, 5, 7, 8, 9};
    int i = 0, j = 6, c = 0;
    while (i < j) {
        int s = a[i] + a[j];
        if (s == 10) { c++; i++; j--; }
        else if (s < 10) i++;
        else j--;
    }
    printf("%d", c);
}
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 5

Correct answer: B. 3

The two pointers find the pairs (1, 9), (2, 8) and (3, 7), and the loop ends when the pointers meet. The pair (5, 5) does not exist because the array holds 5 only once.

More C Programming questions

Exams that ask this topic