Common data questions

Common Data for Questions 48 and 49:

Consider the following recursive C function that takes two arguments.

unsigned int foo(unsigned int n, unsigned int r) {
    if (n > 0) return ((n % r) + foo(n / r, r));
    else return 0;
}

Shared with question 49.

Question

What is the return value of the function foo when it is called as foo(345, 10)?

Choose one option
Official answer and solution
Official answer
B
From
Official GATE 2011 answer key

Solution

Trace the recursive function execution for base 10.

  1. The function foo(n, r) extracts the least significant digit (n%r)(n \% r) in base rr and recurses on n/rn / r, summing all digits until n=0n = 0.
  1. Tracing foo(345, 10):
  • foo(345, 10) = (345 % 10) + foo(34, 10) = 5 + foo(34, 10)
  • foo(34, 10) = (34 % 10) + foo(3, 10) = 4 + foo(3, 10)
  • foo(3, 10) = (3 % 10) + foo(0, 10) = 3 + 0 = 3
  1. Unwinding the recursion:
return value=5+4+3=12\text{return value} = 5 + 4 + 3 = 12
Final answer

B

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2011 Computer Science and Information Technology (CS)
Question
48 of 65, printed as CS Q.48
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.