Discussion
What will be the output of the following C program?
void count(int n){
static int d=1;
printf("%d ", n);
printf("%d ", d);
d++;
if(n\(\gt\)1) count(n-1);
printf("%d ", d);
}
void main(){
count(3);
}
Answer: A
The output is 3 1 2 2 1 3 4 4 4.
The key is that d is static: there is one copy shared by every call, initialized once and never reset.
- count(3) prints 3 and d = 1, then d becomes 2, and calls count(2).
- count(2) prints 2 and d = 2, then d becomes 3, and calls count(1).
- count(1) prints 1 and d = 3, then d becomes 4; since n is not greater than 1 it does not recurse, and prints d = 4.
- Back in count(2), it prints d, now 4; back in count(3), it prints d, 4.
So the sequence is 3 1, 2 2, 1 3, then 4 4 4. Treating d as an ordinary local variable, reset to 1 in each call, gives 3 1 2 1 1 1 2 2 2; the seven-number options forget that every call prints d once more as it returns.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development