TutorialStudyMite
ncr program in C++ | npr program in C++
PPrabhnoor Maingi1 min read
Beginner friendly
Track completion, mastery, and revision.
Program to find NcR NpR
nCr = n! / r!(n-r)! nPr = n! / (n-r)!
Therefore, NPR= NCR*r!
Where C stands for Combinations, and P stands for permutation.
Algorithm
- Prompt the user to input values for
nandrusing thecoutandcinfunctions. - Create a function called
factorialthat takes an integer argument and returns a long int. Inside the function, use a loop to iterate over the range of values from 2 to the input argument, and calculate the factorial using a local variable. - In the main function, use the
factorialfunction to calculatencrasfactorial(n) / (factorial(r) * factorial(n - r)), andnprasncr * factorial(r). - Print the values of
ncrandnpr.
Code
#include <iostream>
long int factorial(int y) {
int i, fact = 1;
for (i = 2; i <= y; i++) {
fact = fact * i;
}
return fact;
}
int main() {
int n, r;
long int ncr, npr;
std::cout << "Enter the value of n: ";
std::cin >> n;
std::cout << "Enter the value of r: ";
std::cin >> r;
npr = factorial(n) / factorial(n - r);
ncr = npr / factorial(r);
std::cout << "NCR value = " << ncr << std::endl;
std::cout << "NPR value = " << npr << std::endl;
return 0;
}
Output
Enter the value of n: 5
Enter the value of r: 2
NCR value = 10
NPR value = 20
Finished reading?