Consider the following C code : #include<stdio.h> int temp=0; int fun(int x, int y) { int z; temp++; if (y==3) return(x*x*x); else { z=fun(x, y/3); return(z*z*z); } } int main() { fun(4, 81); printf("%d", temp); } What will be the output of the above code ?
4
The global variable temp is incremented once at the start of every call of fun, so its final value equals the total number of calls. The recursion stops when y becomes 3; otherwise fun calls itself once with y/3.
| Call | y | temp after increment | Action |
|---|---|---|---|
| 1 | 81 | 1 | calls fun(4, 27) |
| 2 | 27 | 2 | calls fun(4, 9) |
| 3 | 9 | 3 | calls fun(4, 3) |
| 4 | 3 | 4 | returns 4*4*4 |
Step 1 — There are exactly four calls (81 → 27 → 9 → 3), and each increments temp once, so temp = 4 when main prints it.
3 counts only the recursive calls and forgets the first call from main; 5 and 6 add calls that never happen because the chain stops at y = 3.
4 option is correct.
In general, in a recursive and non-recursive implementation of a problem (program) :
Consider the function in C code :
Cal(a, b) {
if (b != 1) {
if (a != 1) {
printf("*");
Cal(a/2, b);
}
else {
b=b-1;
Cal(10, b);
}
}}
How many times * is going to be printed, if the function is called with Cal(10, 10); ?
#include <stdio.h>
int foo(int S[], int size){
if(size == 0) return 0;
if(size == 1) return 1;
if(S[0] != S[1]) return 1 + foo(S + 1, size - 1);
return foo(S + 1, size - 1);
}
int main(){
int A[] = {0, 1, 2, 2, 2, 0, 0, 1, 1};
printf("%d", foo(A, 9));
return 0;
}
The value printed by the given C program is _______ . (Answer in integer)
int func(int start, int end){
int length=end+1-start;
if((length < 1)||(start < 0)||(end < 0)){ return(0); }
if(length%3==0){
return(func(start+1, end));
} else if(length%3==1){
return(1+func(start, end-1));
} else {
return(func(start+2, end));
}
}What is the output of the given C language code snippet?
#include<stdio.h>
void f(int n)
{
if(n==0)
return;
printf("%d ",n);
f(n-1);
}
int main()
{
f(3);
return 0;
}
int bar(int n){
if (n == 1) return 0;
else return 1 + bar(n/2);
}
int foo(int n){
if (n == 1) return 1;
else return 1 + foo(bar(n));
}