+ 1

Can anybody explain how this works?

#include <stdio.h> int main() { int i ; for ( i = 1 ; i <= 5 ; printf ( "\n%d", i ) ) ; i++ ; return 0; }

8th Jul 2020, 5:25 AM
Sri pranavi Donapati
Sri pranavi Donapati - avatar
3 Respostas
+ 3
Hey Sri pranavi Donapati , The for loop syntax is for ( initialisation ; condition ; increment/decrement) { } But it is not compulsory to maintain these steps in this format , you can initialize variables before , you can keep variable increment/decrement in body of for loop also. Here , initialisation is done , then , condition is given , then instead of increment/decrement ; printf() statement is given , so this printf() works 2nd time (First time)--> i=1 then i is less than 5 so it goes inside and does nothing because if you watch carefully, there is ';' after for(); so it indicates empty statement and does nothing therefore , i value is not increamented (Second time)--> i again =1 and less than 5 again condition true therefore it keeps on printing i value without increamenting or decrementing Finally this becomes infinite loop.. Hope you understand..
8th Jul 2020, 5:36 AM
Nikhil Maroju
Nikhil Maroju - avatar
+ 2
Thank u...these explanations helped.
8th Jul 2020, 6:18 AM
Sri pranavi Donapati
Sri pranavi Donapati - avatar
+ 1
You have an infinite loop there. You don't increase value of <i> in the loop, so the loop condition always evaluates to true (<i> value is 1 eternally). The semicolon past the for-loop definition tells the compiler that the loop doesn't have a body, so only the second and third part of the loop definition is executed in repetition. The line `i++;` will never be reached, as the for-loop does not consider that line as part of its loop body, again, this is because of the semicolon past the for-loop definition.
8th Jul 2020, 5:38 AM
Ipang