ProgrammingHardWipro · Cognizant pattern

What is printed? (recursion depth vs. the array being modified on the way back up)

What is printed? (recursion depth vs. the array being modified on the way back up)
int a[5] = {1, 2, 3, 4, 5};
void f(int i) {
    if (i >= 5) return;
    f(i + 1);
    a[i] *= 2;
}
int main(void) {
    f(0);
    for (int i = 0; i < 5; i++) printf("%d ", a[i]);
}
  1. A. 1 2 3 4 5
  2. B. 10 8 6 4 2
  3. C. 2 2 2 2 2
  4. D. 2 4 6 8 10

Correct answer: D. 2 4 6 8 10

All 5 calls recurse fully to the base case before any a[i] *= 2 runs (since the doubling happens AFTER the recursive call), so the doubling happens in order i=4,3,2,1,0 but since each index is independent, every element simply gets doubled once: 2 4 6 8 10.

More C Programming questions

Exams that ask this topic