Problem Solving: Printing a Rectangular Pattern

Let's create a rectangular pattern using a nested for loop.

Printing a rectangular pattern

In this lesson, we’ll learn to print a rectangle using nested for loops.

Let’s say we have to print the following shape:

Height: 3
Width:  10
Symbol: -

----------
----------
----------

To print the above rectangle, we will take width and height as input. In the above shape, the width is 10, the height is 3, and the symbol is '-'.

Idea

We will follow the following strategy:

  • We’ll print the pattern line-by-line with a total of as many lines as the height variable. (3 lines from our example above). For this, we’ll have a for loop counting from 1 till height.
Press + to interact
for(int ln=1; ln<=height; ln++)
{
// Here We will add the code to print the symbols for each line
cout << endl;
}
  • Next, we need to figure out how many symbols we would like to print in each line. Let’s look at the table below to understand the pattern. (We’ll see in the upcoming lessons as well how making tables for each pattern helps writing the code easier).

Rectangular pattern

Line #

No of symbols

1

width (----------)

2

width (----------)

3

width (----------)

.

.

.

.

height

width (----------)

  • As shown in the table, in each line we have printed the symbol character (e.g. -) width time.
    • In coding, that can be done by just writing a simple loop that runs width times (e.g. 10 times), and in each iteration, we need to just print the symbol character.
Press + to interact
.
.
for(int c = 1; c <= width; c++) //In each line print symbol number of time
{
cout << symbol; // print * or any other character
}
.
.
  • After the inner loop, we should print endl because we are done with all printing of that specific line.

  • Now we should repeat these above steps height times.

Here is the code, which does exactly what is described above:

Press + to interact
for(int ln = 1; ln <= height; ln++)
{
for(int c = 1; c <= width; c++)
{
cout << symbol; // print --------
}
cout << endl; // move to the next line
}

Below is the complete program that displays our rectangular pattern.

#include <iostream>
using namespace std;
int main()
{
int width=10,height=3;
char symbol='-';
for(int ln = 1; ln <= height; ln++) // for each line
{
for(int c = 1; c <= width; c++)
//In each line print symbol 'width' times
{
cout << symbol; // print * or any other character
}
cout << endl;
}
return 0;
}
Complete program of printing a rectangular pattern

Instruction: Execute the above program multiple times and change the values of width, height and symbol to see its effect.

Practice exercise

Change the above code to print a square using nested for loops. Your program should print the following shape:

Square size: 5
Symbol: -
-----
-----
-----
-----
-----