
Part-2: Pyramid pattern problems using stars
In this article, we are going to practice some pyramid pattern problems using hash or pound symbol (#). You can use stars(*) instead of this because it’s user choice. I recommend you to please read part-1 of this for a better understanding of this topic.
Topics Covered
- print half pyramid pattern using stars.
- print an inverted half pyramid using stars.
- print half pyramid after 180-degree rotation using stars.
- print full pyramid pattern using stars.
Print half pyramid pattern using stars.
#
# #
# # #
# # # #
# # # # #
Here, the pattern is, we are printing the character in the row by the amount of row number i.e. if row number is equal to 1 then we print one character if row=2 then print 2 characters, and so on. So let’s apply this concept in code.
CODE:
#include<iostream>
using namespace std;
int main()
{
int h;
cout<<"Enter the height of pyramid"<<endl;
cin>>h;
for(int i=1; i<=h; i++)
{
for(int j=1; j<=i; j++)
{
cout<<"# ";
}
cout<<endl;
}
return 0;
}
OUTPUT:
Print an inverted half pyramid using stars.
# # # # #
# # # #
# # #
# #
#
Observe this pattern you realize that this pattern’s concept is just inverse of the previous one. So we just have to do the same as before but print the character at height+1 – row number and we will get the result. Let’s try thiswith code.
CODE:
#include<iostream>
using namespace std;
int main()
{
int h;
cout<<"Enter the height of pyramid"<<endl;
cin>>h;
for(int i=h; i>=1; i--)
{
for(int j=1; j<=i; j++)
{
cout<<"# ";
}
cout<<endl;
}
return 0;
}
OUTPUT:
Print half pyramid after 180-degree rotation using stars.
#
# #
# # #
# # # #
# # # # #
In this question we apply the reverse approach here we print the space rather than characters in out formula and print stars in place of space and got this result. Lets try this with code
CODE:
#include<iostream>
using namespace std;
int main()
{
int h;
cout<<"Enter the height of pyramid"<<endl;
cin>>h;
for(int i=1; i<=h; i++)
{
for(int j=1; j<=h; j++)
{
if(j<=h-i)
{
cout<<" ";
}
else cout<<" #";
}
cout<<endl;
}
return 0;
}
OUTPUT:
Print full pyramid pattern using stars
#
# #
# # #
# # # #
# # # # #
In this pattern we don’t have to apply much effort, just use the previous code, give a space after the character in the code and get our desired output. Let’s apply this in our code.
CODE:
#include<iostream>
using namespace std;
int main()
{
int h;
cout<<"Enter the height of pyramid"<<endl;
cin>>h;
for(int i=1; i<=h; i++)
{
for(int j=1; j<=h; j++)
{
if(j<=h-i)
{
cout<<" ";
}
else cout<<"# ";
}
cout<<endl;
}
return 0;
}
OUTPUT:
In this we discussed some pyramid patterns made with stars. There are many more possibilities of these types of patterns please try as maximum as you can because these can only be improved through practice.
In Part-3, we will discuss pyramid patterns with numbers.