print the pyramidical star pattern in C++
In this tutorial, we will learn to print the pyramidical star pattern in C++.
For Example:
- If n=5.
- The output:
* * * * * * * * * * * * * * *
Approach:
- Firstly, it is a star pattern.
- Now, we have to write the printing function to demonstrate this pattern.
- There will be two for loops.
- The outer for loop will handle the number of rows in that pattern.
- And, the inner loop will handle the number of columns in that pattern.
- The inner loop will depend upon outer for loop and we can say, it will change the values according to outer for loop.
- Finally, it will give you a pyramidical star pattern.
You may also like:
Print alphabet mirror image pattern in C++
print the pyramidical star pattern in C++
Hence, below is the iterative implementation of the above approach.
#include <iostream>
using namespace std;
void pyp(int n)
{
// outer loop
for (int i=0; i<n; i++)
{
// inner for loop will handle number of columns and their values changes acc. to outer for loop
for(int j=0; j<=i; j++ )
{
// print star
cout << "* ";
}
cout << endl;
}
}
int main()
{
int n = 6;
pyp(n);
return 0;
}
OUTPUT EXPLANATION:
INPUT: n=6
OUTPUT:
* * * * * * * * * * * * * * * * * * * * *
After 180 degrees rotation: pyramidical star pattern in C++
Approach:
- Firstly, set k equal to the number of spaces that is approximate twice the value of n.
- Now, the change is, there is three for loops.
- Then, the outer loop will handle the number of rows.
- The first inner loop will handle the number of spaces that will change according to the outer for loop.
- Here, decrement value of k by 2 after each first inner loop.
- Now, the second for loop will handle the number of columns that will change according to the outer for loop.
- Finally, print the stars according to the above approach.
Hence implementation is here:
#include <iostream>
using namespace std;
void pyp2(int nu)
{
int k = 2*nu - 2;
for (int i=0; i<nu; i++)
{
for (int j=0; j<k; j++)
cout <<" ";
k = k - 2;
for (int j=0; j<=i; j++ )
{
// prints
cout << "* ";
}
cout << endl;
}
}
int main()
{
int nu = 6;
pyp2(nu);
return 0;
}
INPUT: nu=6
OUTPUT:
*
* *
* * *
* * * *
* * * * *
* * * * * *
Leave a Reply