This blog is under construction

Tuesday 9 July 2013

C program to calculate ncr and npr


Permutation and Combination Formulas:
nCr = n! / r!(n-r)!
nPr = n! / (n-r)! 



Write a C program to calculate ncr and npr.


  #include <stdio.h>

  /* returns factorial of the given number */
  int fact(int num) {
        int res = 1;
        if (num == 0 || num == 1) {
                return res;
        }

        while (num > 0) {
                res = res * num;
                num--;
        }
        return res;
  }

  int main() {
        int n, r;
        float nPr, nCr;

        /* get the value for n and r from the user */
        printf("Enter the value for n and r:");
        scanf("%d%d", &n, &r);

        /* conbination calculation */
        nCr = (1.0 * fact(n)) / (fact(r) * fact(n-r));

        /* permutation calculation */
        nPr = (1.0 * fact(n)) / fact(n-r);

        /* print the permutation result */
        printf("nPr = %.2f\n", nPr);

        /* print the combination result */
        printf("nCr = %.2f\n", nCr);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/lab_pgms/01_cbasics$ ./a.out
  Enter the value for n and r:10 5
  nPr = 30240.00
  nCr = 252.00




See Also:

1 comment:

  1. It's very useful.Also,helps us if we are confused writing a program it gives us a proper idea how to write a program.

    ReplyDelete