Search code examples
c++loopsvariableswhile-loopstatements

While statements - Cant understand a concept


I am currently learning C++ and right now I am stuck on while statements. The thing is I cant understand properly what is the difference between initializing a variable just before start of the while statement or if the variable is initialized globally in the main.

The piece of code below will probably explain my question better:

int main()
{
using namespace std;
int x = 1;
while (x <= 5)
{
    int y = 1;
    while (y <= x)
    {
        cout << y++ << " ";
    }
    cout << "\n";
    ++x;
}

return 0;

}

This code outputs as:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

but the following

int main()
{
using namespace std;
int x = 1;
int y = 1;
while (x <= 5)
{
    //int y = 1;
    while (y <= x)
    {
        cout << y++ << " ";
    }

    cout << "\n";
    ++x;
}

return 0;
}

produces :

1
2
3
4
5

Well it probably sounds stupid but I really need to understand it. I have gone through a couple of topics but the place of initialization of variable just doesn't get to me in this. If someone can point me out in the right direction, that would be much appreciated. Thanks


Solution

  • y = 1 is initialized again and again when the first while loop starts in the first case.

    In the second case it is not initialized again i.e it reaches the value of x and does not enter the second while loop.