-2

This is my simple while (true) loop:

while (true)  
    {
        int i = 0;
        ++i;
        cout << i << endl;
        if (i == 5) {
            break;
        }
    }
}

So break; isn't quitting the loop and the output is an infinite 1.

Ilan15
  • 27
  • 4

3 Answers3

5

See this for Why use a for loop instead of a while loop?.

Now, coming to your question:

You are initializing i variable in each iteration of your while loop. Move the definition of i outside the while loop so that it's value can be updated.

Try this:

#include <iostream>

int main(void)
{
    int i = 0;
    while (true)  
    {
        ++i;
        std::cout << i << std::endl;
        if (i == 5)
            break;
    }
    return 0;
}

Output:

1
2
3
4
5

Suggestion:

You can also use for loop as it is more appropriate to print a range of numbers.

#include <iostream>

int main(void)
{
    for (int i = 1; i <= 5; i++)
        std::cout << i << std::endl;
    return 0;
}
abhiarora
  • 9,743
  • 5
  • 32
  • 57
0

The i is always initialized to 0 on each iteration. You should use this outside of the loop.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
0

You are creating a new variable i in every run of the loop. It is initalized to zero, then you increase it by one.

So after

int i = 0;
++i;

the variable i is always 1.

Solution:

int i = 0;
while (true) {
    {
        ++i;
        cout << i << endl;
        if (i == 5) {
            break;
        }
    }
}

or you can just use a simple for-loop:

for (int i = 0; i <= 5; i++)  
{
    cout << i << endl;
}
Chromegear
  • 36
  • 3