For Loop explanation!

Hi i have this for loop that out puts a square of "@" depending the size you want it. However I don't understand the loop, like when column is 1 what happens?
Can someone explain it to me?
Thank you for your time!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main () {

int x;
cin>>x;

for(int row=1; row<=x;row++)
{
	for(int column=1;column<=x;column++)
		cout<<"@";
	cout<<endl;
}

return 0;
}

Look at it this way:
1
2
3
4
        for (int column=1; column<=x; column++)
            cout << "@";

        cout<<endl;


At the beginning of the loop, column is set to 1.
Then the condition is tested, (column <= x), if this is true, the body of the loop is executed.
The body of the loop here is the single statement, cout << "@"; which simply outputs a single character to the screen.

Then, control goes back to the top of the loop. column++ is executed, that is the value of column is increased by 1, and then the condition (column <= x) is tested again ... and so on.
So a series of '@' symbols are printed.

Eventually, the value of column will be bigger than x, so the loop terminates, and control passes to the next line cout<<endl;

All of the above has resulted in the printing of a single row of characters, and moving to a new line. Since that code is contained (or nested) within an outer for-loop, then multiple lines will be printed, under the control of that outer loop.
Last edited on
oh great! much appreciated!
Topic archived. No new replies allowed.