C++ Program To Print Pascal’s Triangle (2 Ways)

In this program, we will learn how to print Pascal’s Triangle using the C++ programming language.

What is Pascal’s Triangle?

In mathematics, It is a triangular array of the binomial coefficients. It is named after the French mathematician Blaise Pascal.

Pascal's Triangle
In Pascal’s triangle, each number is the sum of the two numbers directly above it.

We will discuss two ways to code it.

  • Without using Factorial
  • Using Factorial

C++ Programming Code To Print Pascal’s Triangle

Without using Factorial

Code:-

#include<iostream>

using namespace std;
 
int main(){
    int rows, coff;
    cout << "Enter the number of rows : ";
    cin >> rows;
 
    for(int i = 0; i < rows; i++){
        coff = 1;

        for(int j = 1; j < (rows - i); j++){
            cout << "   ";
        }
        
        for(int k = 0; k <= i; k++){
            cout << "      " << coff;
            coff = coff * (i - k) / (k + 1);
        }

        cout << endl << endl;
    }

    return 0;
}

Output:-

Enter the number of rows : 5
                  1

               1      1

            1      2      1

         1      3      3      1

      1      4      6      4      1

Using Factorial

We have already discussed different ways to find the factorial of a number. So, you look up there to learn more about it.

Code:-

#include<iostream>

using namespace std;

long fact(int n){
	int c;
	long res=1;
	for(c=1; c<=n; c++)
	{
		res = res*c;
	}
	return (res);
}

int main(){
    int rows, coff;

    cout << "Enter the number of rows : ";
    cin >> rows;

	for(int i = 0; i < rows; i++){
        for(int j = 1; j < (rows - i); j++){
            cout << "   ";
        }

        for(int k = 0; k <= i; k++){
            coff = fact(i)/(fact(k)*fact(i-k));
            cout << "      " << coff;
        }
		cout << endl << endl;
	}

    return 0;
}

Output:-

Enter the number of rows : 8
                           1

                        1      1

                     1      2      1

                  1      3      3      1

               1      4      6      4      1

            1      5      10      10      5      1

         1      6      15      20      15      6      1

      1      7      21      35      35      21      7      1

You can learn about many other C++ Programs Here.

Best Books for learning C++ programming language with Data Structure and Algorithms.

The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...