Here is a simple C program to print Pascal's triangle.
SOURCE CODE OUTPUT EXPLANATION DOWNLOAD
Previous
Next
SOURCE CODE OUTPUT EXPLANATION DOWNLOAD
#include<conio.h>
long double fact(int);
void main()
{
long a[30][50];
int n,i,j,k;
clrscr();
printf("Enter the number of rows ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(k=2*n+2;k>2*i;k--)
printf(" ");
for(j=0;j<=i;j++)
{
a[i][j]=(long)(fact(i)/(fact(i-j)*fact(j)));
printf(" %2ld ",a[i][j]);
}
printf("\n\n");
}
getch();
}
long double fact(int n)
{
if(n<=1)
return 1;
else
return fact(n-1)*n;
}
long double fact(int);
void main()
{
long a[30][50];
int n,i,j,k;
clrscr();
printf("Enter the number of rows ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(k=2*n+2;k>2*i;k--)
printf(" ");
for(j=0;j<=i;j++)
{
a[i][j]=(long)(fact(i)/(fact(i-j)*fact(j)));
printf(" %2ld ",a[i][j]);
}
printf("\n\n");
}
getch();
}
long double fact(int n)
{
if(n<=1)
return 1;
else
return fact(n-1)*n;
}
SCREENSHOTS
First of all what is pascals triangle ,From the the binomial theorem we have
(a+b)n =nC0anb0+
nC1an-1b1+……………+
nCran-rbr +………….+ nCna0bn
where nCr =n!/(r!*(n-r)!)
thus (a+b)2=a2 +2ab+ b2
in similar way (a+b)3=a3 +3a2
b+3ab2 +b3
from the above equations we get following pattern
1
1 1
1 2 1
1 3 3 1
This is called Pascal’s triangle .Now to print Pascal triangle
we have fact(i)/(fact(i-j)*fact(j)
this is same as the formula we discuss
above .I have used recursion to calculate factorial .Notice that I have
taken the return type of fact functions
long double because through int we can print up to 8 rows only and
using long double we can print up to 30 rows ,also I have type cast the
result and stored in array and than
simply print it .
Any questions regarding to program
please write in comments.
No comments:
Post a Comment