C++ Rectangle

It doesnt show up as a rectangle and I need to use for loop and a nested for loop for this.
So far the code I've got is:

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

int main()
{
	int row, i, width, spaces;

	cout <<"Enter the number of rows: ";
	cin >> row;
	cout <<"Enter the rectangle width: ";
	cin >> width;

	i=0;
	for(i=0; i<row; i++)
		cout << "O";
	cout << endl;	
	for(i=0; i<width; i++)
		cout << "O"<< endl;

	system("pause");
	return 0;
}
Last edited on
And what would you want it to be?
It doesnt show up as a rectangle
That's because you have to nest the for statements as follows:

1
2
3
4
5
6
for(i=0; i<row; i++)
{
    for(j=0; j<width; j++)
        cout << "0";
    cout << endl;
}
Last edited on
still dont get the rectangle
I don't know what you are doing... the following code should defenitely work (tell me if it doesn't):

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

int main()
{
	int row, width, spaces;

	cout <<"Enter the number of rows: ";
	cin >> row;
	cout <<"Enter the rectangle width: ";
	cin >> width;

        for(int i=0; i<row; i++)
        {
            for(int j=0; j<width; j++)
                cout << "0";
            cout << endl;
        }

	system("pause");
	return 0;
}
Last edited on
Ok. I'll dissect the code for you. When I code, I pseudo in English first and then transform that into C++.

print a row of "0"'s
each row contains a column.
we iterate through each column.
once we are done with all the columns in this row
we proceed to the next row.

I think you may have kept the "i" variable in your nested "for" statement - this is why your square didn't work properly and some of your formatting is off.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
using namespace std;

int main()
{
	int row, i, j, width, spaces;

	cout <<"Enter the number of rows: ";
	cin >> row;
	cout <<"Enter the rectangle width: ";
	cin >> width;

        // Print a row of O's
	for(i=0; i<row; i++)
        {
                // Each row has columns iterate them
	        for(j=0; j<width; j++)
                {
                      // Print an "O"
		      cout << "O";
                }
                
                // Done with this row, proceed to next row
                cout << endl;
         }

	system("pause");
	return 0;
}

This code works just fine.
Last edited on
Topic archived. No new replies allowed.