C++ program to print Pascal triangle

In this example, you will learn a c++ program to print Pascal triangle on the screen.  The Pascal triangle is formed by placing 1 along the right and left edges. After that, each value of the triangle is filled by the sum of the above row’s two values just above the given position. This triangle was named after the French mathematician Blaise Pascal.  

Prerequisite

To understand this program perfectly you should have the following C++ programming knowledge.

Program: Print Pascal Triangle

//C++ program to print Pascal triangle
#include<iostream>
using namespace std;

int main()
{
int totalRows,x,y,z,c,place;
	
cout<<"Enter total rows for pascal triangle: ";
cin>>totalRows;
cout<<"\n\n";

place=totalRows;
for(x=0;x<totalRows;x++){
c=1;
for(y=place;y>=0;y--)
cout<<" ";
place--;
for(z=0;z<=x;z++){
cout<<c<<" ";
c=(c*(x-z)/(z+1));
}
cout<<"\n";
}
return 0;
}

Output

Enter total rows for pascal triangle: 5


      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

Description and working of the above program

  • Take total rows for the Pascal triangle from the user and store them in “totalRows”.
  • Initialize for loop for the total number of rows
  • Now initialize two for loops to print the Pascal triangle
  • Terminate program