ncr program in C++ | npr program in C++
Written by
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
n
andr
using thecout
andcin
functions. - Create a function called
factorial
that 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
factorial
function to calculatencr
asfactorial(n) / (factorial(r) * factorial(n - r))
, andnpr
asncr * factorial(r)
. - Print the values of
ncr
andnpr
.
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