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)?
Official answer and solution
- Official answer
- B
- From
- Official GATE 2011 answer key
Solution
Trace the recursive function execution for base 10.
- The function
foo(n, r)extracts the least significant digit in base and recurses on , summing all digits until .
- 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
- Unwinding the recursion:
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.