How to print pascal’s triangle in C++

In this tutorial, we will learn how to print pascal’s triangle in c++. A Pascal’s triangle is a simply triangular array of binomial coefficients. Each number can be represented as the sum of the two numbers directly above it. For example-

Print pascal's triangle in C++

 

Print pascal’s triangle in C++

There are various methods to print a pascal’s triangle. Below is an interesting solution.

If we look closely at the Pascal triangle and represent it in a combination of numbers, it will look like this.

pascals triangle

Look at the 4th line. It follows a pattern. The numbers range from the combination(4,0)[n=4 and r=0] to combination(4,4). This pattern follows for the whole triangle and we will use this logic in our code.

The Formula for combination is simple(shown in image):

formula of pascal's triangle

First, we will calculate the numerator separately and then the denominator.

Note: The first line always prints 1.(So we print it in the main function only)

C++ Code

Here, is the final code implementation:

#include<iostream>
using namespace std;

int res=1;

int fact(int n)
{
    if(n==1||n==0)
    {
        return 1;
    }
    else
    {
        res=n*fact(n-1);
        return res;
    }
}


int combination(int n,int r)
{

    //int num=0,den=0;


    int num=fact(n);

    int den=fact(n-r)*fact(r);

    int result=num/den;


    return result;


}


void pascal(int curline,int nlines)
{
    if(curline==nlines)
        return;



    int k=curline+1;

        for(int j=1;j<=k;j++)
        {
            int dig=combination(curline,j-1);

            cout<<dig<<'\t';
        }
        cout<<endl;

 pascal(curline+1,nlines);

}
int main()
{
    int nlines;
    cin>>nlines;
   
     cout<<"1"<<endl;//The first line always contains 1

      pascal(1,nlines);

}


Input:

6

Output:

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

Also, refer to these similar posts:

Count the number of occurrences of an element in a linked list in c++

Create all possible strings from a given set of characters in c++

Function templates in c++

Thank you! Please comment for suggestions

Leave a Reply

Your email address will not be published. Required fields are marked *