C++ program to print square pattern

In this blog, we will create an article to print square pattern(solid star) in C++.

What is a square pattern?

When an element (which may vary from any sign like star, addition sign, or subtraction sign) gets printed in the same number of rows and columns (let’s say in m rows and m columns) then the pattern formed is known as square pattern.

Algorithm to create the respective code

The code of this program will allow the user to enter the size then the code will display the square pattern of the solid star(*) using for loop in C++ language.

C++ code to print square pattern

#include <iostream>
using namespace std;

int main()
{
    int i,j,size;

    cout << "Please enter the size" << endl;
    cin>>size;//Takes input from the user for size
    for(i=1; i<=size; i++){
        for(j=1; j<=size; j++){
        cout<<"*";
    }
   cout<<"\n";
    }
    
    return 0;
}

Output of the above code

Explanation of the above code

  • This program requests an input size
  • The input (size) is stored in the variable “size”
  • To iterate over a row, go through the outer for loop from 1 to the given size according to the loop structure for(i=1; i<=size; i++)
  • To iterate a row, perform an outer for loop from 1 to the given size according to the loop structure for(j=1; j<=size; j++) ;
  • inside inner loop print asterisk “*”;
  • This activity continues until the outer while loop condition becomes false.