In this article, we will write a **C program to calculate and print the value of nCr**. The formula of nCr is: `nCr = n! / ( r!(n - r)! )`

. For 0 <= r <= n. Here ! represents factorial. For example: 6C2 = 6! / (2! * (6-2)!) => 720/(2 * 24) => 15.

## C Program to print the value of nCr based on user input

In this program, we have defined two functions. The `factorial()`

function is to calculate the factorial, which is required in the `nCr`

formula. The second function `nCr()`

is to calculate the value of `nCr`

, this would use the `factorial()`

function.

#include <stdio.h> /* This function calculates the factorial * of the passed number n and returns it */ unsigned long long factorial(int n) { unsigned long long fact = 1; // Loop to calculate the factorial of n for (int i = 1; i <= n; ++i) { fact *= i; } return fact; } // Function to calculate nCr unsigned long long nCr(int n, int r) { // If r is greater than n, nCr is 0 if (r > n) return 0; // Calculate nCr using the formula: nCr = n! / (r! * (n-r)!) return factorial(n) / (factorial(r) * factorial(n - r)); } int main() { int n, r; // Prompt user to enter the values of n and r printf("Enter value of n: "); scanf("%d", &n); //store the entered value in n printf("Enter value of r: "); scanf("%d", &r); //store the entered value in r // Calculate nCr by calling the function unsigned long long result = nCr(n, r); // Print the value of nCr for entered values of n and r printf("%dC%d = %llu\n", n, r, result); return 0; }

### Output:

Output 1: when value of n is greater than r

Enter value of n: 5

Enter value of r: 2

5C2 = 10

Output 2: when value of r is 0

Enter value of n: 6

Enter value of r: 0

6C0 = 1

Output 3: when value of n and r are same

Enter value of n: 7

Enter value of r: 7

7C7 = 1

Output 4: when value of r is greater than n

Enter value of n: 8

Enter value of r: 9

8C9 = 0

## Leave a Reply