Write an iterative function that calculates the binomial coefficient.
\(C_n^p=\frac{n!}{(n-p)!\times p!}\)
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
int factit(int n)
{
int f; // Result
for (f = 1; n > 1; n--)
f *= n;
return f;
}
int binomialit(int n, int p)
{
return factit(n)/(factit(p)*factit(n-p));
}
void main()
{
int p,n;
printf("n : ");
scanf("%d", &n);
printf("p : ");
scanf("%d", &p);
printf("Version 1 : C_^%d_%d = %d\n", p, n, int binomialit(int n, int p)(n, p));
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Pascal triangle