Sunday, 23 September 2018

Printing an inverted pyramid pattern of an asterisk(*) in C++

Printing inverted 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. Basically, in C++ we print shapes like an 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 inverted pyramid using for loop statement. To print the inverted 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 to any other symbols in place of an asterisk(*).

INVERTED 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<iostream.h>
#include<conio.h>
void main()
{
int i,j,k,n;
clrscr();
cout<<"Enter the number of rows=";
cin>>n;
for(i=1;i<=n;i++)
     {
          for(k=1;k<i;k++)
          {
          cout<<" ";
          }
          for(j=n;j>=i;j--)
          {
          cout<<"* ";
          }
     cout<<"\n";
     }
getch();
}


Output



Program to print the inverted pyramid.
PRINTING OF INVERTED PYRAMID
                               










Explanation

In this program, the user wanted to print no of rows(i.e. n=6). The following cases occurred:

i=1 to 6                k=1 to (i-1)                                                         j=6 to i
1                          k=1 to 0; No space was printed.                        j=6 to 1
                                                                                                       * was printed six times.
2                          k=1 to 1; One space was printed.                    j=6 to 2
                                                                                                       * was printed five times.
3                          k=1 to 2; Two spaces were printed.                  j=6 to 3
                                                                                                       * was printed four times.

The process continued till i=6 and we obtained the inverted pyramid with 6 rows.






No comments:

Post a Comment