Monday, 19 January 2015

Write a program that includes a recursive function to produce a list of binomial coefficients for the power n using the Pascal's triangle technique using C Language.

DESCRIPTION:
                            Binomial coefficients are the numeric factors of the products in a power of a binomial such as (x + y)^n.
For example, (x + y)^2 = x^2+ 2 x y + y^2 has the coefficients 1  2  1. Binomial coefficients can be calculated using Pascal's triangle:
      1               n = 0
    1   1             n = 1
   1  2  1            n = 2
 1  3  3  1           n = 3
1  4  6  4  1         n = 4

Each new level of the triangle has 1's on the ends; the interior numbers are the sums of the two numbers above them.

Write a program that includes a recursive function to produce a list of binomial coefficients for the power n using the
Pascal's triangle technique.
For example,
Input = 2     Output = 1  2  1
Input = 4     Output = 1  4  6  4  1      

Code:

#include "stdio.h"
#include "conio.h"

int fact(int n);
void binomial(int n,int count);
int main()
{
  int n;
  printf("\n\t\t input = ");
  scanf("%d",&n);
  printf("\n\t\t output = ");
  binomial(n,0);
  getch();
}
void binomial(int n,int count)
{   int result;
    if(count<=n){
       result=fact(n)/(fact(n-count)*fact(count));  // binomial coefficient formula= n!/((n-c)! x c!)
       printf(" %d  ",result);        
    }
    else  // when count>n we stop recursion and pointer go back from where it has been called using return;
       return;
    binomial(n,count+1);  // function recursive call and count+1 is increment the counter for calculating next value.
}

int fact(int n)  // function to find factorial of number n.
{
   if(n==0)
     return 1;
   else
     return (n*fact(n-1));
}




// Run this code using devC++.

0 comments:

Post a Comment