Write a C++ program to construct a pyramid and triangle using for loop with output ?

praveen | 2321 Views | c++ | 11 Aug 2016

 

In this article we can print patterns in C++ programming, and also we use two for loops in this example program , the outer for loop and the inner for loop. The outer for loop is responsible for rows and the inner for loop is responsible for columns.

Example 1 : C++ program To Prints The Half Pyramid Using Stars (*)

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int i, j;
 for(i=0; i<5; i++)
 {
  for(j=0; j<=i; j++)
  {
   cout<<"* ";
  }
 cout<<"\n";
 }
 getch();
}

Sample Output :

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

Example 2 : C++ program prints the pattern of stars (*)

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int i, j, k=1;
 for(i=0; i<5; i++)
 {
  for(j=0; j<k; j++)
  {
   cout<<"* ";
  }
  k=k+2;
  cout<<"\n";
 }
getch();
}

Sample Output :

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

Example 3 : C++ program prints the pattern of stars in reverse order(*)

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int i, j, k=8;
 for(i=0; i<5; i++)
 {
  for(j=0; j<k; j++)
  {
   cout<<" ";
  }
  k=k-2;
  for(j=0; j<=i; j++)
  {
   cout<<"* ";
  }
  cout<<"\n";
 }
getch();
}

Sample Output :

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

Example 4 : C++ program print the pyramid of stars (*) with user input

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int i, space, rows, k=0;
 cout<<"Enter the number of rows : ";
 cin>>rows;
 for(i=1; i<=rows; i++)
 {
  for(space=1; space<=(rows-i); space++)
  {
   cout<<"  ";
  }
  while(k!=(2*i-1))
  {
   cout<<"* ";
   k++;
  }
  k=0;
  cout<<"\n";
 }
 getch();
}

Sample Output :

Enter the number of rows : 5
            *
         *  *  *
      *  *  *  *  * 
   *  *  *  *  *  *  *
*  *  *  *  *  *  *  *  *

Example 5 : C++ program prints the inverted half pyramid using stars (*)

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int i, j;
 for(i=0; i<5; i++)
 {
  for(j=5; j>i; j--)
  {
   cout<<"* ";
  }
 cout<<"\n";
 }
getch();
}

Sample Output :

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

Example 6 : C++ program to print half pyramid using continuous characters starting from 'A'.

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int i, j;
 char ch='A';
 for(i=0; i<5; i++)
 {
  for(j=0; j<=i; j++)
  {
   cout<<ch<<" ";
   ch++;
  }
  cout<<"\n";
 }
 getch();
}

Sample Output :

A
B  C
D  E  F
G  H  I  J
K  L  M  N  O