Search code examples
c++while-looptermination

While loop termination overriden?


I have this simple program to calculate number of grains with respect to squares:

#include "library/std_lib_facilities.h"

/*There is an old story that the emperor wanted to thank the inventor of the game of chess and asked the inventor to name
his reward. The inventor asked for one grain of rice for the first square, 2 for the second, 4 for the third, and so on,
doubling for each of the 64 squares. That may sound modest, but there wasn’t that much rice in the empire! Write a
program to calculate how many squares are required to give the inventor at least 1000 grains of rice, at least 1,000,000
grains, and at least 1,000,000,000 grains.*/

int main()
{
    int grains = 1;
    int squares = 1; 

    while(grains < 1000) {
        squares++;
        grains *=2;
        cout << grains << " rice grains for " << squares << " squares" << '\n';
    }
    return 0;
}

The loop prints the grain and square after each loop. This is the output in the terminal:

2 rice grains for 2 squares
4 rice grains for 3 squares
8 rice grains for 4 squares
16 rice grains for 5 squares
32 rice grains for 6 squares
64 rice grains for 7 squares
128 rice grains for 8 squares
256 rice grains for 9 squares
512 rice grains for 10 squares
1024 rice grains for 11 squares

As you can see, the loop termination is greater than the termination condition which is set at grain < 1000.

I don't have any problem with the result, I just want to know why the loop exceeds the termination criteria, why did it not stop at 512 grains? is it because of the iteration of squares in the loop body?


Solution

  • Because

     while(grains < 1000) {  //when grain value is 512, which is true.
            squares++;
            grains *=2;  //become 1024
            cout << grains << " rice grains for " << squares << " squares" << '\n';
        }
    

    instead, you can change your while condition to while(squares < 10)

    or

    int grains = 2;
    int squares = 2; 
    while(grains < 1000) {  //when grain value is 1024, which is false.
                cout << grains << " rice grains for " << squares << " squares" << '\n';
                grains *=2;
                squares++;
    
            }