Note : My Class Teacher gave me this question as an assignment… I am not asked to do it but please tell me how to do it with recursion
Binomial coefficients can be calculated using Pascal’s
triangle:
1 n = 0
1 1
1 2 1
1 3 3 1
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.
Task: 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
done this So Far but tell me how to do this with recursion…
#include<stdio.h>
int main()
{
int length,i,j,k;
//Accepting length from user
printf("Enter the length of pascal's triangle : ");
scanf("%d",&length);
//Printing the pascal's triangle
for(i=1;i<=length;i++)
{
for(j=1;j<=length-i;j++)
printf(" ");
for(k=1;k<i;k++)
printf("%d",k);
for(k=i;k>=1;k--)
printf("%d",k);
printf("\n");
}
return 0;
}
Method 1:
Simplest way is to use the binomial coefficients. With this method, you have 1 recursive method:
Live example.
Method 2:
This method use the construction with the formulae:
Here, the only function is recursive and compute one line at a time, storing these result in an array (in order to cache results).
Live example.
Others methods:
There are some other exotic methods, using the properties of the triangle. You can also use the matrix way to generate it:
No code for it, as it would require a lot of base code (matrices, exponential of matrix, etc…), and it is not really recursive.
On a side note, I think this problem is absolutely not the right problem to teach recursion. There are a lot of better cases for it.