Skip to main content

ProwessApps

Learn · Practice · Excel

C Program 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

C Program 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 nCr (Combinations) factor using a factorial function.

Algorithm / Approach

  1. Read values for n and r.
  2. The mathematical formula for nCr is: n! / ((n-r)! * r!).
  3. Instead of writing three separate loops to calculate three factorials, call the fact() function three times: fact(n) / (fact(n-r) * fact(r)).
  4. Print the result.
main.c
#include<stdio.h>
int fact(int); 

int main(){
 int n,r, res;
 printf("Enter n: ");
 scanf("%d",&n);
 printf("Enter r: ");
 scanf("%d",&r);
 res = fact(n)/(fact(n-r)*fact(r));
 printf("Result nCr Is: %d",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 program perfectly illustrates the power of code reusability.
  • If we didn't have a function, we would have had to write three separate loops in main() to calculate the three different factorials, making the code messy and repetitive.

Complexity

Time Complexity O(n) - Calling factorial multiple times, bounded by n.
Space Complexity O(1)
ADVERTISEMENT