This blog is under construction

Sunday 21 July 2013

C program to calculate ncr using recursion

Write a C program to calculate nCr using recursion.


  #include <stdio.h>

  /* finds factorial of the given number */
  int fact(int num) {
        int ret;

        /* 0! is 1 */
        if (!num) {
                return 1;
        }

        /* recursively call */
        ret = num * fact(num - 1);
        return ret;
  }

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

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

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

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

        /* printing the result */
        printf("Result: %f\n", nCr);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input for n:12
  Enter your input for r:6
  Result: 924.000000


No comments:

Post a Comment