C Program To Calculate The Value of nCr

In this post, we will learn how to calculate the value of nCr using C Programming language.

C Program To Calculate The Value of nCr

nCr means if you are given “n” different items and you have to choose “r” items from it, then nCr gives the total number of ways possible to choose the items.

The Combination formula can also be represented as C(n, r). The formula to compute nCr is = nCr = n! / (r!(n-r)!).

We will be using the same formula in our program to calculate the value of nCr.

So, without further ado, let’s begin the tutorial.

C Program To Calculate The Value of nCr

// C Program To Calculate The Value of nCr
#include <stdio.h>

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

int main(){
    int n, r, nCr;
    
    // Asking for Input
    printf("Enter the value of n: ");
    scanf("%d", &n);
    printf("Enter the value of r: ");
    scanf("%d", &r);
    
    nCr = fact(n) / (fact(r) * fact(n - r));
    printf("The Value of C(%d, %d) is %d.", n, r, nCr);
    
    return 0;
}

Output

Enter the value of n: 7
Enter the value of r: 4
The Value of C(7, 4) is 35.

How Does This Program Work ?

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

In this program, we have defined a custom function named as fact.

    int n, r, nCr;

We have declared three int data type variables named as n, r and nCr.

    // Asking for Input
    printf("Enter the value of n: ");
    scanf("%d", &n);
    printf("Enter the value of r: ");
    scanf("%d", &r);

Then, the user is asked to enter the value of n and r. 

    nCr = fact(n) / (fact(r) * fact(n - r));
    printf("The Value of C(%d, %d) is %d.", n, r, nCr);

We used the combination formula to calculate the value of nCr. Finally, we print the result using printf() function.

Conclusion

I hope after going through this post, you understand how to calculate the value of nCr using C Programming language.

If you have any doubt regarding the program, feel free to contact us in the Comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published.