C++ Program to Print Pascal Triangle

  • Write a C++ program to print pascal triangle.

In this C++ program we will print a Pascal Triangle. Pascal Triangle is a right pyramid of binomial coefficients. Nth row of pascal triangle contains N binomial coefficients. Here is the formulae to find the value of nth element of rth row of pascal triangle.

Pascal triangle formulae

A pascal triangle of 5 rows :
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1
Algorithm to print Pascal triangle
Let N be the number of rows in pascal triangle.
  • We will use nested for loop to print pascal triangle. One iteration of Outer for loop will print one row of triangle.
  • In Kth row of pascal triangle, first we have to print N-K white spaces.
  • After white spaces we will print K space seperated binomial coefficients.
  • At the end of every row, we will print a newline character.

C++ Program to Print Pascal Triangle

// C++ program to print Pascal triangle

#include <iostream>
using namespace std;
   
//Function to calculate factorial of a number 
int getFactorial(int N){
    if(N < 0){
     // Invalid input
        return -1;
    }
    
    int nFactorial = 1, i;
    //  N! = N*(N-1)*(N-2)*(N-3)*.....*3*2*1
    for(i = 1; i <= N; i++){
        nFactorial = nFactorial * i;
    }    
    return nFactorial;
}
   
int main() {  
    int row, rows, i, value;
   
    cout << "Enter Number of Rows of Pascal Triangle\n";  
    cin >> rows;  
   
    for(row = 0; row < rows; row++) {  
        // Print Spaces for every row  
        for(i = row; i <= rows; i++)  
            cout << "  ";  
   
        for(i = 0; i <= row; i++) {  
            value = getFactorial(row)/(getFactorial(i)*getFactorial(row-i));  
            cout << "  " << value;  
        }  
        cout << endl;  
    }  
   
    return 0;  
}
Output
Enter Number of Rows of Pascal Triangle
5
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

In above program, we first take the number of rows in pascal triangle using for loop. Then using for loops we will print the pascal triangle as per above mentioned algorithm. Here we write a getFactorial function which returns the factorial of a number. We are calling this function to calculate binomial coefficients.