Consider the following two functions.
void fun1(int n) {
if(n == 0) return;
printf("%d", n);
fun2(n - 2);
printf("%d", n);
}
void fun2(int n) {
if(n == 0) return;
printf("%d", n);
fun1(++n);
printf("%d", n);
}
The output printed when is called is
View worked solution
Answer: A
To find the output of fun1(5), we trace the execution step-by-step. Note the crucial detail in fun2(n): the call fun1(++n) uses the pre-increment operator. This increments the local variable n in fun2 before passing it to fun1, meaning the subsequent printf("%d", n) in fun2 will print this incremented value.
Let's trace the calls from the bottom up (starting from the base case):
fun2(0): Returns immediately (prints nothing).fun1(2):- Prints
2 - Calls
fun2(0) - Prints
2 - Output:
22
- Prints
fun2(1):- Prints
1 - Increments
nto2and callsfun1(2)(which outputs22) - Prints
2(the incremented value ofn) - Output:
122221222
- Prints
fun1(3):- Prints
3 - Calls
fun2(1)(which outputs1222) - Prints
3 - Output:
312223
- Prints
fun2(2):- Prints
2 - Increments
nto3and callsfun1(3)(which outputs312223) - Prints
3 - Output:
23122233
- Prints
fun1(4):- Prints
4 - Calls
fun2(2)(which outputs23122233) - Prints
4 - Output:
4231222334
- Prints
fun2(3):- Prints
3 - Increments
nto4and callsfun1(4)(which outputs4231222334) - Prints
4 - Output:
342312223344
- Prints
fun1(5):- Prints
5 - Calls
fun2(3)(which outputs342312223344) - Prints
5 - Output:
53423122233445
- Prints
Thus, the final printed output is 53423122233445.
Free practice · Your answers on this page are not saved.
