C++ Program to Compute Combinations using Factorials


The following is an example to compute combinations using factorials.

Example

 Live Demo

#include <iostream>
using namespace std;
int fact(int n) {
   if (n == 0 || n == 1)
   return 1;
   else
   return n * fact(n - 1);
}
int main() {
   int n, r, result;
   cout<<"Enter n : ";
   cin>>n;
   cout<<"\nEnter r : ";
   cin>>r;
   result = fact(n) / (fact(r) * fact(n-r));
   cout << "\nThe result : " << result;
   return 0;
}

Output

Enter n : 10
Enter r : 4
The result : 210

In the above program, the code is present in fact() function to calculate the factorial of numbers.

if (n == 0 || n == 1)
return 1;
else
return n * fact(n - 1);

In the main() function, two numbers of combination are entered by user. Variable ‘result’ is storing the calculated value of combination using factorial.

cout<<"Enter n : ";
cin>>n;
cout<<"\nEnter r : ";
cin>>r;
result = fact(n) / (fact(r) * fact(n-r));

Updated on: 26-Jun-2020

765 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements