unique, ad-free, freemium downloads

18 November 2017

How To Create PASCAL's Triangle in C

PASCAL'S TRIANGLE:



           1
         1   1
       1   2   1
     1   3   3   1
   1   4   6   4   1
Pascal's Triangle can be easily created in C using the formula:
             
                                                   C(n,r) =          n!    
                                                                      (n-r)! r!

In term of rows and column n & r are given as:

n = row & r = col -1
To use above formula you must have a factorial function which can be created by giving its
 prototype and function definition.

CODE :

#include <stdio.h>
#include <stdlib.h>
int fact(int x);// function prototype
int main()
{ int rows ,coef,space;
  printf("Please enter the number of rows of pascal's triangle:");
  scanf("%d",&rows); // In order take the number of rows of the Pascal's Triangle
  for(int row = 1;row<=rows;row++) // for creating rows
  {
    for ( int space=row;space<=rows;space++) // for creating space
     printf("%5s"," ");
      for (int col = 1;col<=row;col++) //for creating columns
       {
        if (col == 1  ) // So that first element of every row is always 1
       {
         printf("%4s%d"," ",col);
       }
      else
     {
      coef = (fact(row - 1))/(fact(row - col)*fact(col -1)); // formula of combination
      if(coef>0 && row != 1 ) /* So that first row should have only 1 element
      result should be printed if combination is greater than zero*/
      printf("%10d",coef);
      }
       }
            puts("");
    }
    system("pause");
    return 0;
}

int fact(int x) // function definition
{   int  factorial = 1;
    for (int a=1;a<=x;a++)
        factorial *= a;
    return factorial ;
}


No comments:

Post a Comment