Saturday, 11 June 2016

Pascal's triangle



Let no = number of rows

Print spaces

For every nth row , print no - n - 1 spaces.

Print numbers

You can find any term in Pascal's triangle by using the below formula
            n!
C(n,r) = ----------       n = row number , r = term number in that row
          r! (n-r)!
If you recall your school maths ,this is the formula for combinations(no of ways of selecting r items from n items).

! stands for factorial.Factorial of an integer is product of the number and all integers below it until 1.
Factorial of 5 = 5 * 4 * 3 * 2 * 1 = 120
#include<stdio.h>

int factorial(int);

int main()
{
    int n,r,no,term;

    printf("Enter no of rows ");
    scanf("%d",&no);

    for(n=0;n<no;n++)
    {
          printf("\n");

          for(r=n;r<no-1;r++)
                printf(" ");

          for(r=0;r<=n;r++)
          {
                term = factorial(n) / (factorial(r) * factorial(n-r));
                printf("%d ",term);
          }

    }

    return 0;
}

int factorial(int n)
{
    int fact=1;

    while(n>=1)
    {
         fact = fact * n;
         n--;
    }
    return fact;
}

1 comment:

  1. sir myself swarali shirodkar from first year comp from goa and i found ur explaination very helpful...sir if u could guide me in c programming i would be obliged...sir pls sir if possible if u could be in contact in terms of mail or any other means of communication would be helpful to me in order to ask doubts.

    ReplyDelete