ncr program in C++ | npr program in C++

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

  1. Prompt the user to input values for n and r using the cout and cin functions.
  2. 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.
  3. In the main function, use the factorial function to calculate ncr as factorial(n) / (factorial(r) * factorial(n - r)), and npr as ncr * factorial(r).
  4. Print the values of ncr and npr.

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

ncr program in C++ | npr program in C++