Generate a hollow rectangle and square pattern with stars in C++

In this shot, we will discuss how to create a hollow rectangle and hollow square pattern with stars in C++.

Solution approach

We will use a nested loop to create a hollow rectangle and hollow square pattern.

A nested loop means there is a loop called outer loop, inside which there is another loop called inner loop. In other words, a loop that calls another loop is called a nested loop.

Let’s look at the visual below that shows the pattern that we will generate.

The image above shows how our hollow rectangle or hollow square will look. We have to input the values for row and column. It will print * at the edges of the rectangle or square, and inside it will be hollow.

Let’s move to the code snippet below to understand it better.

#include <iostream>
using namespace std;
int main() {
int row, column;
cin >> row >> column;
for (int i=1; i<=row; i++)
{
for(int j=1; j<=column; j++)
{
if (i==1 || i==row || j==1 || j==column)
cout << " * " ;
else
cout << " " ;
}
cout << endl;
}
return 0;
}

Enter the input below

Explanation

Note: You need to enter two values with a space in between (row and then column, like so: 4 5 in the above box just below the code.

  • In line 5, we initialize the two variables row and column.

  • In line 6, we take the input as row and column.

  • In line 7, we initialize an outer for loop, where we have given a condition to run the loop for row times.

  • In line 9, we initialize an inner for loop, where we have given conditions to run the loop for column times.

  • In line 11, we give a condition to print *. It will print for the first or last row or for the first or last column; otherwise, it will print blank space as given in the condition.

  • In line 16, we print a next line character. This is done so that the star or blank space gets printed now from the next line onwards.

If we take the number of rows and columns as equal, we will generate a square.

In this way, we can generate the hollow rectangle as well as hollow square patterns using loops in C++.

Note: This pattern can be made with a do-while loop.

Free Resources