C++ Program to print Swastika Pattern
In this C++ tutorial, we will see how to print Swastik pattern from given number n, the pattern of n height using loops.
Note- N, an odd number (>=5).
Print Swastik Pattern
Divide the given pattern into two parts from the middle. Now do the work of these parts separately and print the required pattern accordingly.
Examples :
n=7
* * * * *
* *
* *
* * * * * * *
* *
* *
* * * * *Code:
First, we calculate mid because it should be divided into 5 parts – using nested loops.
- Top line – our loop print top line if(i==1) we print * and then when j>mid.
- Between Top and Middle – we print * for only when j==1 and j== mid.
- Middle line- we print the whole line with *.
- Between Middle and Bottom – we print * for h== mid and j==n.
- Bottom Line – we print * for j<=mid
#include<iostream>
using namespace std;
int main(){
int n=11;
int mid= (n/2)+1;
for(int i=1;i<=n;i++){
//top line
if(i==1){
cout<<"* ";
for(int j=2;j<=n;j++){
if(j<mid){
cout<<" ";
}
else{
cout<<"* ";
}
}
cout<<endl;
}
//between top and middle
if(i!=1 && i<mid){
for(int j=1;j<=n;j++){
if(j==1 || j==mid){
cout<<"* ";
}
else{
cout<<" ";
}
}
cout<<endl;
}
//middle line
if(i==mid){
for(int j=1;j<=n;j++){
cout<<"* ";
}
cout<<endl;
}
//between middle and bottom
if(i>mid && i!=n){
for(int j=1;j<=n;j++){
if(j==mid || j==n){
cout<<"* ";
}
else{
cout<<" ";
}
}
cout<<endl;
}
//bottom line
if(i==n){
for(int j=1;j<=n-1;j++){
if(j<=mid){
cout<<"* ";
}
else{
cout<<" ";
}
}
cout<<"* ";
}
}
}
Now its time to run our program. So let’s see what we will see after we run the program:
* * * * * * *
* *
* *
* *
* *
* * * * * * * * * * *
* *
* *
* *
* *
* * * * * * *We can see that our Swastik pattern done correctly with the C++ program and we can see the result in the console.
Leave a Reply