Printing upright pyramid of symbols
A pattern is an array formed by repeating, serial or recurring elements. Elements like numbers, symbols or characters may form a pattern. Patterns basically are well organized and systematic. Patterns can be of various shapes and sizes. In C++ we print shapes like the upright pyramid, inverted pyramid, rectangle, flag, and right-angled triangle. The basic concept used to print pattern in C++ is the use of nested for loop statement.
Write a program in C++ to print an upright pyramid pattern of asterisk.
In this program, we will print an upright pyramid using for loop statement. To print the upright pyramid we will need three for loop statements. The first loop is for the execution of no of rows, the second loop is for the printing of spaces and the third loop is for the execution of no of columns. You can use the same method for any other symbols in place of an asterisk(*).
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,k,n;
clrscr();
cout<<"Enter number of rows of pyramid= ";
cin>>n;
for(i=1;i<=n;i++)
{
for(k=n;k>i;k--)
{
cout<<" ";
}
for(j=1;j<=i;j++)
{
cout<<"* ";
}
cout<<"\n";
}
getch();
}
UPRIGHT PYRAMID
*
* *
* * *
* * * *
* * * * *
* *
* * *
* * * *
* * * * *
Nested loop
If we use a loop inside a loop then it is called a nested loop. It is implemented by considering a new loop as a statement of the previous loop.
Syntax:
for (condition 1)
{
for(condition 2)
{
{
for (condition 3)
{
.
.
.
.
}
}
}
}
}
Program
#include<conio.h>
void main()
{
int i,j,k,n;
clrscr();
cout<<"Enter number of rows of pyramid= ";
cin>>n;
for(i=1;i<=n;i++)
{
for(k=n;k>i;k--)
{
cout<<" ";
}
for(j=1;j<=i;j++)
{
cout<<"* ";
}
cout<<"\n";
}
getch();
}
Output
PRINTING OF AN UPRIGHT PYRAMID |
Explanation
In this program, the user wanted to print 6 no of rows(i.e. n=6). The following cases occurred:
i=1 to 6 k=6 to (i+1) j=1 to i
1 k=6 to 2; Five spaces were printed. j=1 to 1
* was printed once.
2 k=6 to 3; Four spaces were printed. j=1 to 2
* was printed twice.
3 k=6 to 4; Three spaces were printed. j=1 to 3
* was printed thrice.
i=1 to 6 k=6 to (i+1) j=1 to i
1 k=6 to 2; Five spaces were printed. j=1 to 1
* was printed once.
2 k=6 to 3; Four spaces were printed. j=1 to 2
* was printed twice.
3 k=6 to 4; Three spaces were printed. j=1 to 3
* was printed thrice.
The process continued till i=6 and we obtained the upright pyramid with 6 rows.
Fact about c++
C++ programming language was also called 'The New C' when it was introduced.
No comments:
Post a Comment