What is printed by this C code: int f(int n) { return n == 0 ? 0 : n % 10 + f(n / 10); } printf(“%d”, f(1234));?
Correct answer D. 10
Explanation
Each call adds the last digit (n % 10) and recurses on the remaining digits (n / 10), and the base case n == 0 returns 0. So f(1234) = 4 + 3 + 2 + 1 + 0 = 10. 4321 would be a digit reversal and 24 is the product of the digits. Every recursive function needs a base case that is reached for all inputs, otherwise the calls would overflow the stack.
Answer checked How we write and check questions
Discussion