Practice mode C Language

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.