Related Tags

c++
pattern
loop
communitycreator

# Generate a filled rectangle and square pattern with stars in C++

Vinisha Maheshwari

In this shot, we are going to discuss how to use stars in C++ to create a filled rectangle and square pattern.

## Solution approach

We will use a nested loop to create a rectangle and 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 see the image below that shows the pattern that we will generate.

Solid Rectangle and Solid Square Patterns

In the image above, for the case of rectangle, the number of rows is four and the number of columns is five, which means the number of rows is not equal to the number of columns.

In the same way, if we take the number of rows and columns as equal, we will generate a square.

Let’s see the code snippet below to understand this 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++)
cout << " * ";
cout << endl;
}
return 0;
}

Enter the input below

Generate a filled rectangle and square pattern using stars in C++

## Explanation

Note: In the input box above, you must enter two values for row and column with a space in between, like so: 4 5

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

• In line 6, we take the inputYou need to enter the two values in the above box just below the code 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 8, we initialize an inner for loop, where we have given conditions to run the loop for column times.

• In line 9, we print the *. This star will be printed column times.

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

In this way, we can make solid rectangle as well as square patterns using loops in C++.

RELATED TAGS

c++
pattern
loop
communitycreator

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time