What will be the output of the following program?
void count (int n) {
static int d=1;
printf ("%d",n);
printf ("%d",d);
d++;
if (n>1) count (n-1);
printf ("%d",d);
}
void main(){
count (3);
}View worked solution
Answer: A
To find the output of the program, we need to trace the execution of count(3). Note that d is a static variable, which means it is initialized only once (at the start of the program) and retains its value across all recursive function calls.
Step-by-Step Trace:
-
First Call:
count(3)(where )dis initialized to .- Prints and :
3and1.
Current Output:31 - Increments
dto . - Since (), it calls
count(2).
-
Second Call:
count(2)(where )dis currently .- Prints and :
2and2.
Current Output:3122 - Increments
dto . - Since (), it calls
count(1).
-
Third Call:
count(1)(where )dis currently .- Prints and :
1and3.
Current Output:312213 - Increments
dto . - Since () is false, it skips the recursive call.
- Prints
d:4.
Current Output:3122134 count(1)finishes and returns tocount(2).
-
Resuming
count(2)- Prints
d: Sincedis static and currently , it prints4.
Current Output:31221344 count(2)finishes and returns tocount(3).
- Prints
-
Resuming
count(3)- Prints
d: Sincedis static and currently , it prints4.
Current Output:312213444 count(3)finishes.
- Prints
Thus, the final output is 3 1 2 2 1 3 4 4 4.
Free practice · Your answers on this page are not saved.
