Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to find out ncr factor by using a user defined function for factorial.

FORMULA : ncr = n! / ((n-r)! * r!)

C++ Code Example — Function Programs

ADVERTISEMENT

WAP to find out ncr factor by using a user defined function for factorial.

FORMULA : ncr = n! / ((n-r)! * r!)

Objective

Write a C++ program to calculate the combinations formula (nCr) using a Factorial function.

Algorithm / Approach

  1. Define a fact() function.
  2. In main(), read n and r.
  3. Calculate nCr using the mathematical formula: fact(n) / (fact(n-r) * fact(r)).
  4. Print the result.
main.cpp
#include<iostream>
using namespace std;
int fact(int);

int main(){
 int n,r, res;
 cout<<"Enter n: ";
 cin>>n;
 cout<<"Enter r: ";
 cin>>r;
 res = fact(n)/(fact(n-r)*fact(r));
 cout<<"Result nCr Is: "<< res;
}

int fact(int x){
 int i, f=1;
 for(i=1; i<=x; i++){
  f = f*i;
 }
 return f;
}

Expected Output

Enter n: 5
Enter r: 3
Result nCr Is : 10

Explanation of the Program

  • This perfectly demonstrates the power of reusable functions.
  • The combinations formula (nCr) requires calculating three separate factorials. Instead of writing three separate for loops in our main code, we simply call our reusable fact() function three times in a single mathematical equation!

Complexity

Time Complexity O(n) - Because fact(n) is O(n).
Space Complexity O(1)
ADVERTISEMENT