Search code examples
c++for-loopnested-for-loop

Why does this nested for-loop print this?


I need to figure out how this nested for-loop outputs:

1
2
3
2
4
2
3
5
2
3
4
#include <iostream>
using namespace std;

int main()
{
    int x, y;
    for (x = 1; x <= 5; x++)
    {
      cout << x << endl;
      for (y = 2; y < x; y++)
        cout << y << endl;
    }
}

Solution

  • The problem here is that you don't seem to understand which value is 'x' and which one is 'y':

    You can easily understand this by replacing following lines of code:

    cout << x << endl;
    

    by

    cout << "x: " << x << endl;
    

    And

    cout << y << endl;
    

    by

    cout << "y: " << x << endl;