In this article, we will write a **C program to calculate and print the value of nPr**. The formula is: `nPr = n! / (n - r)!`

, here ! represents factorial. For example 6P2 = 6! / (6-2)! => 720 / 24 = 30.

## C Program to print the value of nPr based on user input

In this program, we have defined two functions. The `factorial()`

function is to calculate the factorial, which is required in the `nPr`

formula. The second function `nPr()`

is to calculate the value of `nPr`

, this uses `factorial()`

function.

#include <stdio.h>

/* This function calculates the factorial

* of the passed number n and returns it

*/

unsigned long long factorial(int n) {

unsigned long long fact = 1;

// Loop to calculate the factorial of n

for (int i = 1; i <= n; ++i) {

fact *= i;

}

return fact;

}

// Function to calculate nPr

unsigned long long nPr(int n, int r) {

// If r is greater than n, nPr is 0

if (r > n) return 0;

// Calculate nPr using the formula: nPr = n! / (n-r)!

return factorial(n) / factorial(n - r);

}

int main() {

int n, r;

// Prompt user to enter the value of n and r

printf("Enter value of n: ");

scanf("%d", &n); //store entered value in n

printf("Enter value of r: ");

scanf("%d", &r); //store entered value in r

// Calculate nPr

unsigned long long result = nPr(n, r);

// Print the value of nPr

printf("%dP%d = %llu\n", n, r, result);

return 0;

}

### Output:

Output 1: when value of n is greater than r

Enter value of n: 5

Enter value of r: 2

5P2 = 20

Output 2: when value of r is 0

Enter value of n: 10

Enter value of r: 0

10P0 = 1

Output 3: when value of r is greater than n

Enter value of n: 4

Enter value of r: 5

4P5 = 0

## Leave a Reply