Q90.Marks: +2.0UGC NET Paper 2: Computer Sc 23rd August 2024 Shift 1
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);
return 0;
}
What will be the output of the above code ?
1.3
2.4✓ Correct
3.5
4.6
Solution
The correct answer is 4
Concept:
This problem involves understanding recursion in C and how global variables are affected by recursive function calls. The function `fun` is a recursive function that increments a global variable `temp` each time it is called. The recursion continues until `y` is no longer divisible by 3, at which point the function returns a value and the recursion unwinds.
Explanation:
Let's break down the code step by step:
#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);
return 0;
}
1. `fun(4, 81)` is called.
2. `temp` is incremented to 1. Since `y` (81) is not 3, the function calls `fun(4, 81 / 3)` i.e., `fun(4, 27)`.
3. `temp` is incremented to 2. Since `y` (27) is not 3, the function calls `fun(4, 27 / 3)` i.e., `fun(4, 9)`.
4. `temp` is incremented to 3. Since `y` (9) is not 3, the function calls `fun(4, 9 / 3)` i.e., `fun(4, 3)`.
5. `temp` is incremented to 4. Now, since `y` (3) is equal to 3, the function returns `4 * 4 * 4` which is 64.
6. This return value (64) is then cubed at each level of recursion as it unwinds, but these return values do not affect the global `temp` variable.
The total number of times `fun` is called before reaching the base case is 4. Therefore, the value of `temp` is 4.