C++ Program to Compute Combinations using Factorials

C++ProgrammingServer Side Programming

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));
raja
Published on 06-Nov-2018 09:25:04
Advertisements