C program to find the value of nCr for a given value of n & r

In this C Programming example, we will implement the program to find the value of nCr for a given value of n & r and print the output on the console.

1. What is nCr in Probability – Mathematics?

nCr is a probability function that represents combination, it states the selection of ‘r‘ elements from a group or set of ‘n‘ elements, such that the order of elements does not matter. The formula to find combinations of elements is- 

nCr = n!/(r! * (n-r)!)
Here,
n = the total number of items or net size.
r = It is the subnet size or total number of items chosen from sample. 
Example:
Input 
n: 8
r: 4

Formula 
8!/(4! * (8−4)!)
= 8!/(4! * 4!) 
= 40320/(24*24)
= 70

Output
4 C 3 is 70

Helpful topics to understand this program better are-


2. C Program to find the value of nCr for a given value of n & r

Let’s discuss the execution(kind of pseudocode) for the program to find the value of nCr for a given value of n & r in C.

  1. Initially, the program will prompt the user to enter the values of n and r.
  2. Now, we invoke the function int nCr(int n, int r), within this function, we call int fact(int n) function to calculate the required factorial values.
  3. Factorial values are used to calculate the nCr value and then we print this value on the console.

In this C Programming example, we have discussed how to find the value of nCr for a given value of n & r in C.

#include <stdio.h>
int fact(int n);

int nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); }

// This functions returns factorial of n
int fact(int n) {
  int res = 1;
  for (int i = 2; i <= n; i++) {
    res = res * i;
  }
  return res;
}
int main() {
  int n, r;
  printf("Enter the value of n: ");
  scanf("%d", &n);
  printf("Enter the value of r: ");
  scanf("%d", &r);

  printf("The value of %dC%d is %d", n, r, nCr(n, r));
  return 0;
}

Note: Only whole positive integer numbers are valid.

Output
Enter the value of n: 5
Enter the value of r: 4
The value of 5C4 is 5

3. Conclusion

In this C Programming example, we have discussed how to find the value of nCr for a given value of n & r in C and discussed the steps of the program in detail.


Helpful Links

Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.

Also for the example C programs please refer to C Programming Examples.

All examples are hosted on Github.


Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index