Friday, 27 April 2012

Printing the Pascal's triangle in C



Here is a program that generates a Pascal's Triangle! Just in case you don't know what a Pascal's Triangle is, don't worry. Look below.
In general, the nth row of the Pascal's Triangle consists of the binomial coefficients nCr, with r=0,1,2,3,4, ... n. 


      1
   1   1
1   2   1
 1   3   3   1
1   4   6   4   1

#include<stdio.h>
#include<conio.h>


long factorial(int);


int main()
{
int i,c,n;

printf("Enter the number of rows you want in the Pascal's Triangle: \n\n");
scanf("%d",&n);

for(i=0;i<n;i++)
{
for(c=0;c<(n-i);c++)
{
printf("  ");
}
for(c=0;c<=i;c++)
{
printf("%ld  ",factorial(i)/(factorial(i)/factorial(i-c)));
}
printf("\n\n");
}
getch();
return 0;
}


long factorial(int n)
{
int c;
long result=1;

for(c=1;c<=n;c++)
{
result=result*c;
}
return(result);
}

No comments:

Post a Comment