Pascal Triangle in C programme I wrote this in c to find pascal triangle value.
ID: 3813503 • Letter: P
Question
Pascal Triangle in C programme
I wrote this in c to find pascal triangle value. However when the row is larger than 30 it has negative output. What's wrong with my code ?
Thanks
HERE IS MY CODE:
// find the Bionomial coefficient
int pascal(int row, int r){
int result = 1;
if(r > n-r){
r = n-r;
}
for( int i = 0; i < r; ++i){
result =result*(n-i);
result = result/(i+1);
}
return result;
}
// print the pascal triangle
for(int row = 0; row <= line; row++) {
for (int i = 0; i <= row; i++) {
printf("%d", pascal(row, i));
printf(" ");
}
printf(" ");
}
Explanation / Answer
#include <stdio.h>
#include <math.h>
long Fact(int);
int main()
{
int i, Num, j;
printf(" No. of Rows ");
scanf("%d", &Num);
for (i = 0; i < Num; i++)
{
for (j = 0; j <= (Num - i - 2); j++)
{
printf(" ");
}
for (j = 0; j <= i; j++)
{
printf("%ld ", Fact(i) / (Fact(j) * Fact(i-j)));
}
printf(" ");
}
return 0;
}
long Fact(int Num)
{
int i;
long Fact = 1;
for (i = 1; i <= Num; i++)
Fact = Fact * i;
return Fact;
}