retagged by
10,827 views
23 votes
23 votes

Consider the following $\text{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 ______.

retagged by

5 Answers

Best answer
41 votes
41 votes
int main() {
        calc(4, 81);
        printf("%d", counter);
}
printf("%d", counter);
So we need only counter value.
Each function increments counter value by 1. Goal is to find the number of function calls.
Squence of function calls:
calc(4, 81) ---> calc(4, 27) ---> calc(4, 9) ---> calc(4, 3) ---> return

4 function calls.
counter = 4
edited by
8 votes
8 votes

There is no need to calculate return value we just need value of counter.

So answer is 4.

3 votes
3 votes
#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);
}

Here counter is a global variable, you can use anywhere of the program, 

 Now when main() call the calc() by the value (4,81) 

--> counter=counter+1 so now counter=1.

Now for 81 not eq to 3 so else block got executed and Now b=81/3=27.

Again counter increased by 1 and now counter =2.

In this way when b=3 counter will become 4 and cacl() return 64;

counter=3

int calc(4,3)

{

int c;

counter++;

if(b==3) return (a*a*a);
        else {
                c = calc(a, b/3);
                return (c*c*c);
        }

}

So, ans is 4.

2 votes
2 votes
The main function is just printing counter value. There's no need to calculate the values of return statements in the function calc().

 

Therefore , Answer is 4.
Answer:

Related questions

4 votes
4 votes
3 answers
1
GO Classes asked Mar 26, 2022
563 views
What will be the output printed by $\text{mystery}3(6)$?void mystery3(int n) { if (n == 0 || n == 1) return; mystery3(n-2); printf("%d", n); mystery3(n-1); }
42 votes
42 votes
9 answers
2
35 votes
35 votes
7 answers
3