Program for printing the half pyramid of * in C++
Program for printing the half pyramid of * in C++
#include<iostream>
using namespace std;
int main()
{
int r;
int i,j;
cout<<"Enter values for r=";
cin>>r;
for(i=0;i<r;i++) //this for loop starts from 0 and ends at i=r
{
for(j=i;j>0;j--) //this for loop starts from at j=i and ends at j=1
{
cout<<"*"; // prints *
cout<<" "; //prints space after each *
}
cout<<endl; //enter in new line
cout<<"\t";
}
cout<<"\t";
}
output:
Enter values for r=6
*
* *
* * *
* * * *
* * * * *
If we want the inverted half pyramid of * we have to make some changes in the above code in the for loops.
Program for inverted half pyramid :
#include<iostream>
using namespace std;
int main()
{
int i,j,n,m=0;
cout<<"enter number of rows : "; //prints the msg in "" between this
cin>>n; //stores the value in n
for(i=n;i>=1;--i) // for loop starts with n and ends at 1
{
for(j=1;j<=i;++j) //starts from 1 and ends at i value
{
cout<<"*"<<" "; //prints * and space after it
}
cout<<endl; //new line it works like enter in keyboard
}
return 0;
}
output:
enter number of rows : 6
* * * * * *
* * * * *
* * * *
* * *
* *
*
Comments
Post a Comment