Question
Consider the following C program:
#include <stdio.h>
int counter = 0;
int calc (int a, int b) {
int c;
counter++;
if (b==3) return (a*a*a);
else {
c = calc(a, b/3);
return (c*c*c);
}
}
int main (){
calc(4, 81);
printf ("%d", counter);
}
The output of this program is _____.
Official answer and solution
- Official answer
- 4
- From
- Official GATE 2018 answer key
Solution
Trace the recursive calls to count how many times the function is invoked.
The function calc(a, b) increments the global variable counter upon entry, checks if , and if not, recursively calls calc(a, b/3).
Trace the recursive invocations starting from calc(4, 81):
calc(4, 81):counterbecomes 1. Since , callscalc(4, 27).calc(4, 27):counterbecomes 2. Since , callscalc(4, 9).calc(4, 9):counterbecomes 3. Since , callscalc(4, 3).calc(4, 3):counterbecomes 4. Since , base case is reached and returns without further recursion.
The total number of invocations is 4, so counter equals 4.
Final answer
4
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2018 Computer Science and Information Technology (CS)
- Question
- 31 of 65, printed as CS Q.21
- 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.