Consider the following 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 ______.
View worked solution
Answer: 4
To find the output of the program, we trace the execution of the recursive function calc(4, 81) and track the value of the global variable counter.
The function calc(a, b) increments counter by 1 on every entry. Let's trace the sequence of recursive calls:
- First Call:
calc(4, 81)counteris incremented to 1.- Since , the
elsebranch is executed. - It calls
calc(4, 81/3), which iscalc(4, 27).
- Second Call:
calc(4, 27)counteris incremented to 2.- Since , the
elsebranch is executed. - It calls
calc(4, 27/3), which iscalc(4, 9).
- Third Call:
calc(4, 9)counteris incremented to 3.- Since , the
elsebranch is executed. - It calls
calc(4, 9/3), which iscalc(4, 3).
- Fourth Call:
calc(4, 3)counteris incremented to 4.- Since , the base condition
if(b == 3)is satisfied. - It returns and begins unwinding the recursion.
After all recursive calls complete and return, the final value of counter printed by the main function is 4.
Free practice · Your answers on this page are not saved.
