Pascal's Triangle in C++

C++Server Side ProgrammingProgramming

Pascal’s triangle is an array of binomial coefficients. The top row is numbered as n=0, and in each row are numbered from the left beginning with k = 0. Each number is found by adding two numbers which are residing in the previous row and exactly top of the current cell. It is also being formed by finding (𝑛𝑘) for row number n and column number k.

Suppose the input is 10, then the output will be like −

               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
     1 8 28 56 70 56 28 8 1
   1 9 36 84 126 126 84 36 9 1

To solve this, we will follow these steps.

  • for i := 0 to n
    • for j = 0 to n – i – 2, print black space
    • for j := 0 to i, perform nCr(i, j)

Let us see the following implementation to get a better understanding −

Example (C++)

 Live Demo

#include<iostream>
#include<iomanip>
using namespace std;
long fact(long n){
   int i, fact = 1;
   for(i = n; i>1; i--)
      fact *= i;
   return fact;//factorial of given number
}
long nCr(long n, long r){
   long nume = 1, i;
   for(i = n; i>r; i--)
      nume *= i;
   return long(nume/fact(n-r));//generate result of nCr
}
void genPascalsTriangle(long n){
   for(int i = 0; i<n; i++){
      for(int j = 0; j<(n-i-1); j++)
         cout <<setw(3)<< " ";//printing space to show triangular form
      for(int j = 0; j<(i+1); j++)
         cout <<setw(3)<< nCr(i, j) <<setw(3)<< " ";
      cout << endl;
   }
}
main(){
   int n;
   cout << "Enter Number of lines: "; cin >> n;
   genPascalsTriangle(n);
}

Input

10

Output

                        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
               1 8 28 56 70 56 28 8 1
             1 9 36 84 126 126 84 36 9 1
raja
Published on 08-Jan-2020 10:15:49
Advertisements