I was just wondering why this :
int i;
for (i=0; i<5; i++){
printf("%d\n",i)
}
printf("Here i get the result that misleads me : %d\n",i)
The last value is 5.
My logic is :
From 0 to 4 -> printf
If i > 4 (since we are dealing with integers) stop the loop.
But the loop stopped at 4 not 5 ! Why do I get 5 after the loop ? Why does it ever increment ?
Arbitrary ?
Thanks,
There are three clauses in the for statement.
So, end of each for loop execution, increment operation executed, and, in the 4th iteration, value of i is 5 and the for loop was broke as the value is 5 in 5th iteration.
unroll what's happening
int i = 0;
while( i < 5 )
{
// body of for loop
i++;
}
// i == 5 here as i must be greater than or equal to 5 to break out of while loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With