What is the output of the following program ? #include<stdio.h> int main(){…
2023
What is the output of the following program ?
#include<stdio.h>
int main(){
int i = 3;
while(i --){
int i=10;
i --;
printf("%d",i);
}
printf("%d",i);
}
- A.
990
- B.
9990
- C.
999 - 1
- D.
99 - 1
Attempted by 157 students.
Show answer & explanation
Correct answer: C
Step-by-step reasoning:
The outer variable i is initialized to 3.
The condition while(i--) uses post-decrement: it checks the current value of i, then decrements it. With i starting at 3, the loop body runs for i = 3, 2, and 1, so there are three iterations; after these iterations the outer i becomes 0.
Inside the loop a new inner variable i is declared and initialized to 10. This inner i shadows the outer i inside the loop body.
The inner i is decremented once (i--), becoming 9, and printf prints that value. This happens on each of the three iterations, producing three '9' characters.
After the loop finishes, the outer i is -1, and the final printf prints '-1'.
Final output: 999 -1