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]);
}- A. 1 2 3 4 5
- B. 10 8 6 4 2
- C. 2 2 2 2 2
- 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
- What is printed? (recursion with an early return skipping the rest of the function) c int f(int n) { if (n < 0) return -1; if (n == 0)…
- What is printed? (binary string of n using recursion, division by 2) c void toBinary(int n) { if (n == 0) return; toBinary(n / 2)…
- What is printed? (two mutually exclusive recursive branches selected by a condition, with accumulation via return value) c int f(int n) {…
- What is printed? (recursion where the base case is reached via an off-by-one condition) c int f(int n) { if (n < 1) return 0; return n +…
- What is printed? (recursion with a pointer parameter used only for read, not accumulation) c int maxOf(int a[], int n) { if (n == 1)…
- What is printed? (recursive function returning a computed value through a chain of ternaries) c int classify(int n) { return n == 0 ? 0…