In this shot, we are going to discuss how to use stars in C++ to create a filled rectangle and square pattern.
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.
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
Note: In the input box above, you must enter two values for
row
andcolumn
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 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++.