Consider the following C program: #include <stdio.h> int counter = 0; int calc…
2018
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 _____.
Attempted by 147 students.
Show answer & explanation
Correct answer: 4
Key idea: each call to calc increments the global counter. The function recurses by dividing b by 3 until b equals 3.
First call: calc(4, 81). counter becomes 1. Since 81 != 3, it calls calc(4, 81/3) = calc(4, 27).
Second call: calc(4, 27). counter becomes 2. Since 27 != 3, it calls calc(4, 27/3) = calc(4, 9).
Third call: calc(4, 9). counter becomes 3. Since 9 != 3, it calls calc(4, 9/3) = calc(4, 3).
Fourth call: calc(4, 3). counter becomes 4. Now b == 3, so this is the base case and the function returns without further recursion.
Therefore, the global counter is incremented exactly four times and the program prints 4.
A video solution is available for this question — log in and enroll to watch it.