'Why does i print the same value as the number I want less than?

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

c++


Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

Because the i in while(i < 10) stays in the loop til i is equals to 10, i compares the values with 10 so when it reaches 10 it will break out of the loop and it would print it out

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bathsheba
Solution 2 molbdnilo
Solution 3 Jam