BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C program to calculate and print the value of nPr

Last Updated: May 22, 2024 by Chaitanya Singh | Filed Under: C Programs

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

Related C Programs:

  • C Program to calculate and print the value of nCr
  • C Program to search substring in a given string
  • C Program to multiply two complex numbers
  • C Program to print numbers divisible by 3 and 5 from 1 to 100
  • C Program to check abundant number

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap