Program to draw Pascal triangle in C++

Drawing different shapes like triangles, diamonds, pyramids etc. is the very basics of programming and are very important to learn and understand. Let’s start our program to draw Pascal Triange in C++ programming code.

For other triangle, diamonds & Pyramid shapes see –> Patterns and Shapes in C++

 

We will make our program to draw pascal triangle to get following output as result

           1
         1   1
       1   2   1
     1   3   3    1
   1  4    6   4   1
 1  5   10   10  5   1

Program:

#include <iostream>
using namespace std;
int main()
{
    int rows,coef=1,space,i,j;
    cout<<"Enter number of rows: ";
    cin>>rows;
    for(i=0;i<rows;i++)
    {
        for(space=1;space<=rows-i;space++)
        cout<<"  ";
        for(j=0;j<=i;j++)
        {
            if (j==0||i==0)
                coef=1;
            else
               coef=coef*(i-j+1)/j;
            cout<<"    "<<coef;
        }
        cout<<endl;
    }
}

 

Leave a Reply