This is a C Program to calculate the value of nCr.
This C Program Calculates the value of nCr.
The algorithm used in this program is nCr = n! /((n-r)!r!). Here we need to find all the possible combination of the value n and r. A combination is one or more elements selected from a set without regard to the order. The “without regard” means that the collection matters rather than order in combinations, so in the above example, the fact we ABC, ACB, BAC, BCA, CAB, CBA… for combinations, these are all 1 combinationof letters A, B and C.
Here is source code of the C program to Calculate the value of nCr. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C program to Calculate the value of nCr */ #include <stdio.h> int fact(int z); void main() { int n, r, ncr; printf("\n Enter the value for N and R \n"); scanf("%d%d", &n, &r); ncr = fact(n) / (fact(r) * fact(n - r)); printf("\n The value of ncr is: %d", ncr); } int fact(int z) { int f = 1, i; if (z == 0) { return(f); } else { for (i = 1; i <= z; i++) { f = f * i; } } return(f); }
In this C Program, we are reading the value for ‘n’ and ‘r’ variable to calculate the value of nCr. The algorithm used in this program is nCr = n! /((n-r)!r!). A combination is one or more elements selected from a set without regard to the order.
Then ‘ncr’ variable is used to compute fact(n)/(fact(r)* fact(n – r)). The fact() function is used to compute the factorial of the value. If-else condition statement is used to check the argument value of ‘z’ variable is equal to 0. If the condition is true then execute the statement.
For loop is used to compute the factorial value. Initialize the value of ‘i’ variable to 1 and check the value of ‘i’ variable is less than or equal to the argument value in ‘z’ variable. If the condition is true then execute the loop. Multiply the value of ‘f’ variable with each integer variable value in ‘i’ variable. Compute the value for nCr and print the value of nCr using printf statement.
Output: $ cc pgm12.c $ a.out Enter the value for N and R 5 2 The value of ncr is: 10
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Apply for Computer Science Internship
- Check C Books
- Practice BCA MCQs
- Check Computer Science Books
- Apply for C Internship