GATE 2018 CS – Question 31
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 ________.
Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: 4
Explanation
Each call of `calc(a, b)` increments `counter`, then either returns (if `b==3`) or calls `calc(a, b/3)`.
| call | b |
|---|---|
| 1 | 81 |
| 2 | 27 |
| 3 | 9 |
| 4 | 3 (stops) |
So `calc` is called 4 times and `counter` $=\mathbf4$.