The triangle of Pascal is a numerical triangle formed by binomial numbers (n k)
where it represents the number of the line and represents the number of the column, beginning to count to 0. The triangle of Pascal shows symmetry in relation to the height, if it is written of the following
form:
1
1 1
1 2 1
1 3 3 1
Knowing that each coefficient (n k)
can be calculated recursively by the following formula:
C (n, k) = C (n - 1, k - 1) + C (n - 1, k)
C (n, n) = C (n, n) = 1
implement a (recursive) function that calculates its binomial coefficient and use this function in its main program to print the n lines of the Pascal Triangle.
#include <stdlib.h>
#include <stdio.h>
int pascal(int n, int k);
int main()
{
printf("%d\n",pascal(5, 5));
return 0;
}
int pascal(int n, int k){
if(n == k || n == 0){
return 1;
}else{
return pascal(n - 1, k - 1) + pascal(n - 1, k);
}
}
The second condition in the if statement should be k==0 rather than n==0. (Not critical here, but might be worth returning 0 if k>n or k<0 as well.)
You are only printing out one coefficient: 5,5. You want nested loops to print the rest.
This is probably what your assignment asks for, but it's a bit inefficient as every coefficient is computed multiple times to get others. Compiling a table would be more efficient.