C++ | Drawing a pyramid using loop

Introduction

As i promised in earlier post to give a program to draw a real pyramid in c++. I am fulfilling the promise. This program draws a pyramid. The program is extendable. There is no need to input anything. Go enjoy the program. Lets begin………

A program to print the pyramid


#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int
int i,a,s=5,m;
//print triangle
for(i=1;i<=5;i++)
{
m=s;
while(s>0)
{
cout<<" ";
s--;
}
for(a=1;a<=i;a++)
{
cout<<"* ";
}
cout<<endl;
s=m-1;
}
//get character
getch();
}

Output

    *
   * *
  * * *
 * * * *
* * * * *

How does it work

No need to input anything. Directly prints the triangle.

Extending it

The program can be extended by using different symbols instead of ‘*’ in program. Go ahead and extend it…..

Even you can invert the pyramid and make parallelogram using two pyramids….

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare the variables as int (name them as you want.)
  5. Add the loop for number of rows.
  6. Print the spaces.
  7. Add loop inside the loop added before for number of columns.
  8. Print the symbol.

At the end

You learnt creating the c++ program of Drawing a pyramid in c++. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: