Permutation and Combination – C PROGRAM

In one of my posts on C Programming, I showed, how to calculate the Factorial of a number.

In this post we will use that program, and extend it to calculate the Combination ^nC_r and the Permutation ^nP_r .

If you haven’t read the post on factorial calculation, then you can check it out here.

Now, a combination is defined as:
^nC_r = \frac{n!}{r!(n-r)!}

and the Permutation is defined as:
^nP_r = \frac{n!}{(n-r)!}

So we will have the user enter their choice, and then prompt the user to enter the r and n
and then return the answer based on their choice.

The program is pretty simple and can be written as shown below.



/*Function that calculates the factorial of a given integer n */
double factorial(int n){
  int i;
  double fact=1;
  return fact;

int main(){
  int n,r,choice;
  printf("\n\nType 1 for Permutation and \n2 for Combination\n");
    printf("Enter n and r for nPr\n");
    scanf("%d %d",&n,&r);
      printf("Sorry! r should be smaller than n\n");
      return 0;
    printf("The permutation (%dP%d)= %f\n",n,r,factorial(n)/factorial(n-r));
  }else if(choice==2){
    printf("Enter n and r for nCr\n");
    scanf("%d %d",&n,&r);
      printf("r should be smaller than n\n");
      return 0;
    printf("The combination (%dC%d)= %f\n",n,r,factorial(n)/(factorial(n-r)*factorial(r)));
    printf("\nPlease enter a valid choice!\n");

As one can see, the program is pretty much self-explanatory.


Some sample outputs have been attached below:

PhD researcher at Friedrich-Schiller University Jena, Germany. I'm a physicist specializing in theoretical, computational and experimental condensed matter physics. I like to develop Physics related apps and softwares from time to time. Can code in most of the popular languages. Like to share my knowledge in Physics and applications using this Blog and a YouTube channel.
[wpedon id="7041" align="center"]

5 thoughts on “Permutation and Combination – C PROGRAM

Leave a Reply

Your email address will not be published. Required fields are marked *