ProgrammingHardProduct company OA

What is printed?

What is printed?
int a[] = {1, 1, 2, 3, 3, 3, 4}, k = 1;
for (int i = 1; i < 7; i++)
    if (a[i] != a[k - 1]) a[k++] = a[i];
printf("%d %d", k, a[k - 1]);
  1. A. 4 4
  2. B. 7 4
  3. C. 4 3
  4. D. 3 3

Correct answer: A. 4 4

k is the length of the de-duplicated prefix. A value is copied only when it differs from the last value kept, so the prefix becomes 1 2 3 4 and k = 4; a[k − 1] is 4. This works only because the array is sorted.

More C Programming questions

Exams that ask this topic