1

I tried to code a program that will give the pascal triangle without using arrays and keeping in mind the formula that each element of the pascal triangle can be calculated as n choose k" and written like this: n choose k = n! / k!(n-k)! (for both n and k starting from 0)

so I also had to define the factorial function and it worked for the first 14 lines. but in line 15 and more my numbers started to decrease and became also negative but I don't understand why this happened.

Here is the code:

#include <stdio.h>
int factorial(int a);

int main()
{
    int row, j, i, space, tot;
    scanf("%d", &row);
    space=row;
    for(i=0; i<row; i++)
    {
        for(space=0; space<row-i; space++)
        {   printf("   ");    }

        for (j = 0; j <= i; j++)
        {
            if (j == 0 || i == 0)
            {   tot=1;  }
            else
            {   
                int n=factorial(i);
                int k=factorial(j);
                int z=factorial(i-j);
                tot= n/(k*z);
            }
            printf("%6d", tot);
        }
        printf("\n");
    }
}

int factorial(int a)
{
    int fact=1;
    for (int m=1; m<=a; m++)
        {   fact*=m;    }
    return fact;
}

this is my output in line 15: 1 0 1 5 14 29 44 50 44 29 14 5 1 0 1

but the actual output should be this: 1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1

I couldn't find the problem so I would be happy and thankful if anyone could help me.

Rosha. R
  • 31
  • 5

1 Answers1

0

If you don't care much about computation time then you could compute coefficient directly from their recursive definition.

int pascal(int x,int y) {
   if (x==0 || y==0) return 1;
   return pascal(x-1,y)+pascal(x,y-1);}
tstanisl
  • 13,520
  • 2
  • 25
  • 40