C program to calculate permutations and combinations

C program to calculate permutations and combinations

``````#include <stdio.h>

// declare the functions we are going to use
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);

int main(){

int n = 0;
int r = 0;
long nCr, nPr;

printf("Enter the value of n and r\n");
scanf("%d,%d",&n,&r);

nCr = find_ncr(n, r);
nPr = find_npr(n, r);

int nf = factorial(n);
int rf = factorial(r);

printf("%d! = %d\n", n, nf);
printf("%d! = %d\n", r, rf);

printf("%dC%d = %ld\n", n, r, nCr);
printf("%dP%d = %ld\n", n, r, nPr);

return 0;
}

// define the functions declared above

// function to find combinations
long find_ncr(int n, int r){

long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;

}

// function to find permutations
long find_npr(int n, int r){

long result;
result = factorial(n)/factorial(n-r);
return result;

}

// function to find factorial of a number
long factorial(int n){
int c;
long result = 1;

for( c = 1 ; c <= n ; c++ )
result = result*c;
return ( result );
}
``````