ProgrammingVery hardProduct company OA

What is printed?

What is printed?
struct N { struct N *nx; } n[5];
for (int i = 0; i < 4; i++) n[i].nx = &n[i + 1];
n[4].nx = &n[2];
struct N *s = n, *f = n;
int steps = 0;
do { s = s->nx; f = f->nx->nx; steps++; } while (s != f);
printf("%d %td", steps, s - n);
  1. A. 2 2
  2. B. 4 2
  3. C. 3 2
  4. D. 3 3

Correct answer: D. 3 3

The list is 0 → 1 → 2 → 3 → 4 → back to 2. Slow and fast pointers: after step 1 they are at 1 and 2, after step 2 at 2 and 4, after step 3 at 3 and 3, where they meet. The meeting point is inside the cycle but need not be its start (2).

More C Programming questions

Exams that ask this topic