Simple Pattern Program in C++

In this article, we are going to learn about how to print a basic pattern with “*” and maths numbers. Pattern programs are a good exercise to master the loops in the C++ language. Here in this example, we will try to print two types of patterns.

  • Using * , print a square matrix box where user enters the size.
  • Using Numbers , print a square matrix box where user enters the size.

1. Print square matrix box value entered by the user


In this example, we will print the square matrix with the help of for loop and “” astrik character. User will enter the size of this square matrix box and we will print the box with the help of ““.

Desired Output for size 3:-

* * *
* * *
* * *

First we are asking user to enter his desired size, once the user enter the size we save it in a variable. Then we iterate on two for loops
to the max of this input value from user.
For each iteration we are printing the “*” n times for the nth iteration.On each row iteration we switch to next line using “\n”.

#include <iostream>
using namespace std;
int main()outp
{
   int num;

   cout<<"Please enter the size of Square Box: ";
   cin>>num;

   for(int row=1; row<=num; row++)
   {
     for(int col=1; col<=num; col++)
     {
       cout<<"* ";
     }
     cout<<"\n";
   }
   return 0;
}

Actual Output:

Please enter the size of Square Box: 5
* * * * * 
* * * * * 
* * * * * 
* * * * * 
* * * * * 

2.Print a square matrix box of number size entered by user


This is another variant of the program above, to print a square matrix box. In this example, we will not make use of “*” instead we will use the actual numbers.so the logic will remain same as in above example, only change will be the output characters from * to numbers.

1 2 3
1 2 3
1 2 3
#include <iostream>
using namespace std;
int main()
{
   int num;

   cout<<"Please enter the size of Square Box: ";
   cin>>num;

   for(int row=1; row<=num; row++)
   {
     for(int col=1; col<=num; col++)
     {
       cout<<col;
     }
     cout<<"\n";
   }

   return 0;
}

Actual Output:

Please enter the size of Square Box: 5
12345
12345
12345
12345
12345