C++ Program to Print Pascal Triangle


Pascal triangle is a very important mathematical concept. It is named after French mathematician Blaise Pascal. A Pascal triangle is used to find the coefficients of a binomial expansion.

In this example, we create a simple program to print a Pascal triangle.

This program is intended for intermediate learner of C++ programming language. We used Dev C++ compiler version 4.9.9.2 installed on Windows 7 64-bit system to compile and test the program.

Problem Definition

A typical binomial look like the following, because it has only two variables – a and b.

 

(a + b)^2 = a^2 + 2ab + b^2

 

The right-hand equation is called the binomial expansion. Each of the binomial expansion terms have a coefficient.

 

a^2 = coefficient is 1.

2ab = coefficient is 2.

b^2= coefficient is 1.

 

Pascal Triangle

The Pascal triangle display all coefficients of all powers from 0 for a binomial expansion.

 

(a + b)^n

 

Where n is the power of binomial whose coefficient we want to know.

Diagram - Pascal Triangle
Diagram – Pascal Triangle

The top (n = 0) is one has a coefficient of 1. The coefficient of 4th row (n = 4) 2nd element is 6.

You can find coefficient of any term by adding previous two terms just above the term you are looking for.

Get coefficient of 3rd row and 1st term = 3

Get coefficient of 3rd row and 3rd term = 3

Add them together and you get

Coefficient of 4th row and 2nd term = 6

Formula

There is a formula for finding the coefficient of any term – given the row (n) and the term (r);

nCr = n! / r! (n – r)!

To understand the formula and C++ program, you must learn these two mathematical concepts.

  1. Factorial
  2. Combination

We have used the formula of a coefficient to find coefficients of all the rows in this program.

Program Code – Pascal Triangle

#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
int p, j;
int row, lines, element, term;
cout << "Enter Number of Rows in Pascal Triangle:";
cin >> lines;
 
 
 
int fact (int);
for (row = 0; row < lines; row++)
{
for (j = 0; j <= (lines - row - 2); j++)
cout << " ";
 
for (element = 0; element <= row; element++)
{
p = row - element;
term = fact (row)/ (fact (element)* fact (p));
 
cout << " " << term;
 
 
}
cout << "\n";
}
getch ();
return 0;
}
/* Factorial Function */
int fact (int x)
{
if (x == 1 || x == 0)
{
return 1;
}
else
{
return (x * fact(x-1));
}
}

Output – Pascal Triangle

The output of the program is given below. The program requires that you input the number of row. A row is equal to power of a binomial. The program prints all the coefficients of all the previous rows.

 

Output - Pascal Triangle
Output – Pascal Triangle