In C, what does this recursive function return for the input 123, and why is the result printed twice? #include<stdio.h> int sumdig(int); int main() { int a, b; a = sumdig(123); b = sumdig(123); printf("%d, %d ", a, b); return 0; } int sumdig(int n) { int s, d; if(n!=0) { d = n%10; n = n/10; s = d+sumdig(n); } else return 0; return s; }

Difficulty: Easy

Correct Answer: 6, 6

Explanation:


Introduction / Context:
The function sumdig recursively computes the sum of the decimal digits of its input. The program calls the function twice with the same constant, then prints both results, testing understanding of recursion and base cases.


Given Data / Assumptions:

  • Input n = 123.
  • Base case: if n == 0, return 0.
  • Recursive case: s = (n % 10) + sumdig(n / 10).


Concept / Approach:
Digit sum decomposition uses integer division and modulo to peel off the least significant digit each call. The recursion terminates when n becomes 0, at which point unwinding adds each digit.


Step-by-Step Solution:
Call sumdig(123): d = 3, recurse with 12.sumdig(12): d = 2, recurse with 1.sumdig(1): d = 1, recurse with 0.sumdig(0) returns 0 (base case).Unwind: s(1) = 1 + 0 = 1; s(12) = 2 + 1 = 3; s(123) = 3 + 3 = 6.Both a and b receive 6; print "6, 6".


Verification / Alternative check:
Non-recursive check: 1 + 2 + 3 = 6, confirming the computed result.


Why Other Options Are Wrong:
"4, 4" and "3, 3" are partial sums; "12, 12" incorrectly sums digits by concatenation or multiplication. "0, 0" contradicts the nonzero input.


Common Pitfalls:
Forgetting to return 0 at the base case or misplacing the return outside the if/else can cause undefined values. Here the structure is correct and yields 6 consistently.


Final Answer:
6, 6

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion