Permutation Program In C


Advertisements

Permutation refers number of ways in which set members can be arranged or ordered in some fashion. The formula of permutation of arranging k elements out of n elements is −

nPk = n! / (n - k)!

Algorithm

This algorithm only focuses on permutation without going into details of factorial −

START
   Step 1 → Define values for n and r
   Step 2 → Calculate factorial of n and (n-r)
   Step 3 → Divide factorial(n) by factorial(n-r)
   Step 4 → Display result as permutation
STOP

Pseudocode

This algorithm can simply be derived into the below given pseudocode −

procedure permutation()
   
   Define n and r
   P = factorial(n) / factorial(n-r)
   DISPLAY P 

end procedure

Implementation

Implementation of this algorithm is given below −

#include <stdio.h>

int factorial(int n) {
   int f;

   for(f = 1; n > 1; n--)
      f *= n;

   return f;
}

int npr(int n,int r) {
   return factorial(n)/factorial(n-r);
}

int main() {
   int n, r;

   n = 4;
   r = 3;

   printf("%dp%d = %d \n", n, r, npr(n,r));

   return 0;
}

Output

Output of the program should be −

4p3 = 24 
mathematical_programs_in_c.htm
Advertisements