I need to create a rectangle using for loop and a nested for loop
So far the code I've got is:

#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;
}

Recommended Answers

All 2 Replies

As the problem instructions say, you need to have the second loop nested inside the first loop. in this case, all you really need do is remove the two cout lines between the loops, and move the endl off of the the inner loop's output, and you should be good to go:

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

You may need to modify this slightly if you need to make a box rather than a filled rectangle.

Note that it is almost always best to explicitly brace any blocks, even when there is only one following statement inside the block. The only real exception to this that I can think of is when using the if/else if/else idiom.

As the problem instructions say, you need to have the second loop nested inside the first loop. in this case, all you really need do is remove the two cout lines between the loops, and move the endl off of the the inner loop's output, and you should be good to go:

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

You may need to modify this slightly if you need to make a box rather than a filled rectangle.

Note that it is almost always best to explicitly brace any blocks, even when there is only one following statement inside the block. The only real exception to this that I can think of is when using the if/else if/else idiom.

Next time try to guide him please.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.