In this article, we are going to learn about how to print Character Patter in C++ Language using ASCII 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.
- Print a square matrix box of numbers where the user enters the size.
- Print a square matrix box of characters where the user enters the size.
1. Print a square matrix box of number size entered by the user
In this example, we will print the square matrix with the help of for loop and numbers. We will ask the user to enter the size and then we will print the square matrix using numbers. First, we are asking the user to enter his desired size, once the user enters the size we save it in
a variable. Then we iterate on two for loops to the max of this input value from the user. For each iteration of the row, we are iterating on full column length and printing the row number. On each row iteration, we switch to the next line using “\n”.
#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<< row;
}
cout<< "\n";
}
return 0;
}
Actual Output:
Please enter the size of Square Box: 4
1111
2222
3333
4444
2. Print a square matrix box number to characters size entered by the user
In this example, we will print the square matrix with the help of for loop and characters. We will ask the user to enter the size and then we will print the square matrix using characters. This is similar to the above example, but here we are making use of the ASCII codes of the numbers
to print them in character form.
Desired Output:
a a a
b b b
c c c
First, we are asking the user to enter his desired size, once the user enters the size we save it in a variable. Then we iterate on two for loops to the max of this input value from the user. For each iteration of the row, we are iterating on full column length and printing the row number+96.
This 96 is taking us to the ASCII code of this row number and we are printing this number as a character by using a character conversion specifier. On each row iteration, we switch to the next line using “\n”.
#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<< char(row + 96);
}
cout<<"\n";
}
return 0;
}
Output
Please enter the size of Square Box: 4
aaaa
bbbb
cccc
dddd