Consider
#include <iostream>
int main()
{
int i = 0;
while (i < 10)
i ;
std::cout << i << endl;
}
I just wanted to know, why does this print out 10? if it is i < 10, shouldn't it be 9 that is printed? I appreciate any help
CodePudding user response:
Because when i
is 9, (i < 10)
is true
, so the while
body runs, which increments i
by 1 thereby setting it to 10. Sure, on that last iteration of the while
body, i
is an expression equal to 9, but with the side-effect of increasing i
.
CodePudding user response:
Regardless of what happens inside the loop,
do this as long as
i
is less than 10
is the same as
do this until
i
is greater than or equal to 10
So the value of i
after the loop must be (at least) 10, since that's when it stops.