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

NOTE:- The output shown below is of pyramid, my blog is deleting the spaces automatically so its not drawn properly here, but i promise that the program above will draw it in your software.

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

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s