Search code examples
c++gccfor-loopubuntu-10.10

Mystifying For-Loop Error


I am using Ubuntu 10.10, Codeblocks IDE, and gcc compiler. I noticed the program I am writing was creating some odd output. Eventually I narrowed the issue down to a for-loop in the program. I was surprised to discover that the following basic for-loop didn't perform as expected.

#include <iostream>

using namespace std;

int main()
{


for(unsigned int i = 0; i < 21; i++)
    {
    cout << i << endl;
    }

return 0;

}

When I compile and run it, the output is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Although one would expect the output should include zero. Very surprisingly, when I change the for loop to

#include <iostream>

using namespace std;

int main()
{


for(unsigned int i = 0; i < 20; i++)
    {
    cout << i << endl;
    }

return 0;

}

I get the expected output of:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

I can't for the life of me figure out why 21 (and all numbers greater than 21) give me this false output, while 20 (and lower numbers) don't. If anyone has run into anything like this before, I'd sure appreciate hearing how he/she worked around it.


Solution

  • maybe the screen just scroll?

    try to redirect the output to a text file