# Pascal’s Triangle using C program

Printing Pascal’s Triangle is a famous problem in C. You may be familiar with the Pascal triangle from the Math class when you learned Permutation and Combination or Binomial Coefficients or other class. If you are not familiar then don’t worry, just look at Wikipedia to get inside of the Pascal Triangle and see the code below.

There are various methods to generate Pascal’s Triangle in C program. Among them the most popular one is by using Combination. Since elements of the triangle represent the Binomial Coefficients of a polynomial and Binomial Coefficient can be calculated using the Combination, I decided to generate Pascal’s Triangle using Combination method. Here is the source code

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #include<stdio.h> #include<conio.h> /*************************************************** Program that prints the Pascal Triangle for the given number fo rows. @author Bibek Subedi 5/6/2013 ***************************************************/ /**************************************************** returns the factorial of number n @param n @return the factorial of n ****************************************************/ int factorial(int n){ int fact = 1; int i; for(i = n; i > 0; i--){ fact = fact*i; } return fact; } /*************************************************** returns the combination or Binomial Coefficient of n, r i.e return C(n,r) @param n size @param r elements taken from n @return C(n,r) ***************************************************/ int combination(int n,int r){ int comb; comb = factorial(n)/(factorial(n-r)*factorial(r)); return comb; } int main(){ int r, i = 0, j = 0, comb; /// number of rows of Pascal's Triangle printf("Enter the number of rows: "); scanf("%d",&r); for(i = 0; i < r; ++i) { for (j = 0; j < r - i; ++j) { printf(" "); } for(j = 1; j <= i; ++j) { comb = combination(i,j); printf("%d ", comb); } printf("\n"); } return 0; } |

Another method to calculated Pascal’s Triangle is using the fact that “Each number in the triangle is the sum of the two directly above it.” This is illustrated by the following GIF image taken from Wikipedia.

## Recent Comments