## Monday, May 6, 2013

### Pascal’s Triangle using C program

Printing Pascal’s Triangle is famous problem in C. You may be familiar with the Pascal triangle from the Math class when you learnt 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 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

#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.