nested while-loop + undetermined error
I was working on a problem and able to detect the source. So, I keep isolating until I got the short code that caused me to buzz my head.
Here is the code:
Code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int power=1;
int i=1;
int counter=1;
while (i<=10)
{
cout << "i = " << i << endl;
while (counter<=(10-i))
{
power *= 2;
counter++;
}
cout << power << endl;
i++;
}
return 0;
}
If I replaced counter <= i, the program will output correctly
In order to replicate my program, I tweaked it to be counter <= (10-i), then it started to screw up.
I thought this is weird, since I analyzed it this way:
At i=1, j=1, then power = 2
At i=1, j=2, then power = 4
......
At i=1, j = 9, then power = 2^9 = 512
------------------------------------------------
At i=2, similarly, at the end of the inner-loop, j=8, the power should be 256?
Perhaps, I misconcept something??
Any hints will be so useful!
THanks! :)