0
3.5kviews
What do you mean by Recursion? Write a program which will accept two numbers, n and r and calculate value of $nC_r$ = n! / r! (n - r)!. Program should make use of recursion.
1 Answer
1
163views

Recursive Function:

  • A function that calls itself is called as recursive function.
  • A recursive function must definitely have a condition that exists from calling the function again.
  • Hence there must be a condition that calls the function itself if that condition is true.
  • If the condition is false then it will exit from the loop of calling itself again.

Algorithm:

Main () Function:

  • Start.
  • Enter values of n and r to be printed”.
  • Input n and r.
  • Using formula of nCr = fact(n)/fact(n-r);
  • C = CALL (k*fact(k-1));
  • Print nCr.
  • Stop.

Exponential (parameters: x, y)

  • Start.
  • If k=1, then return 1.
  • Else return(kCALL (kfact(k-1)))
  • Stop.

Program:

#include <stdio.h>
#include <conio.h>
int main(){
    int n, r, C;
    int fact(int k);
    printf("Enter the number n and r:");
    scanf("%d%d", &n, &r);

    C = fact(n)/fact(n-r);
    printf("nCr=%d\n", C);
    getch();
}
int fact(int k) {
    if(k==1)
    return 1;
    else
    return (k*fact(k-1));
}

Output:

Enter the number n and r = 5 3

$nC_r$ = 60

Explanation:

  • In this program, to get value of nCr, we just divide fact(n) with fact(n-r).
  • This is done by the recursive function “fact”.
  • It checks the value of the index, if it is equal to 1, then it returns just the value 1.
  • Else it passes the value of nCr by calling itself i.e. recursive function.
Please log in to add an answer.