+ 1

Explain the Output

#include <stdio.h> int main() { int i; for ( i=0; i<5; i++ ) { int i = 10; printf ( "%d ", i ); i++; } return 0; } Here answer is 5 times 10 can anyone explain how?

18th Sep 2020, 3:04 PM
Samir Singh
Samir Singh - avatar
4 Respuestas
+ 4
the scope of the inner i(int i = 10) is only within the for loop and has got nothing to do with the for loop initialize, condition and increment part. Why five 10 as output? so basically after we print i inside the for loop, i is incremented but notice in the next iteration again we are assigning i with 10 (this line i = 10). hence we have 10 10 10 10 10. do read and play with scope of variable to know what's going on behind the scene. Please avoid duplications https://www.sololearn.com/Discuss/2504162/?ref=app
18th Sep 2020, 3:39 PM
minirkk
minirkk - avatar
+ 2
I would first recommend you to avoid using same variable name to prevent misunderstanding. You have <i> in main function block, another <i> as the for-loop counter, and yet another <i> inside the for-loop body. But I can understand if that came from a challenge.
18th Sep 2020, 3:35 PM
Ipang
0
First you should understand the difference between int i (outside the for loop) , and 2nd int i (inside the for loop) this printing 5 times becoz you've give the condition to for loop is less than 5. Postfix isn't working many times.
18th Sep 2020, 5:35 PM
Rupali Haldiya
Rupali Haldiya - avatar