Accelerated C++ Solution to Exercise 2-6

Exercise 2-6

What does the following code do?

int i = 0;
while (i < 3)
{
    i += 1;
    std::cout << i <<std::endl;
}

Solution

This is very a classic usage of while loop with the following properties:

Invariant i, with the initial integer value of zero.

int i = 0;

And asymmetric range [0,3). i.e. invariant i is incremented at a specified interval (in this case 1) from the initial value of 0 to the ending value of 3 (but excluding 3). Note the mixed use of square and round brackets (in the sense of writing in the post rather than the actual code.). We use square brackets [ ] to imply inclusiveness, and round bracket ( ) to imply exclusiveness.

while (i < 3)    // asymmetric range of [0,3)
{
    i += 1;     // invariant increment interval is 1
    std::cout << i <<std::endl;   // display the invariant to the standard output console
}

I denote this while loop as i [0,3)

Using logic, I’d expect the code to do this:

Invariant i (at top of loop) while ( i < 3) i += 1 Console Output
0 true 1 1
1 true 2 2
2 true 3 3
3 false

To confirm this let’s run the following code and output result.

#include <iostream>

int main()
{
     int i = 0;
     while (i < 3)
     {
         i += 1;
         std::cout << i <<std::endl;
         //i += 1;
     }
     return 0;
}

Result

1
2
3

The nice thing about using asymmetric range [0,N) is the ease of understanding. i.e. The invariant is true for N number of loops.

Extras

Say now if we modify the code so that the invariant increment happens at the bottom. i.e.

int i = 0;
while (i < 3) {
    std::cout << i <<std::endl;
    i += 1;
}

Our result should now look like this:

Invariant i (at top of loop) while ( i < 3) Console Output i +=1
0 true 0 1
1 true 1 2
2 true 2 3
3 false

We run the modified code and it confirms our expectation:

0
1
2

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Leave a reply