C Program To Calculate The Value of nPr

In this post, we will learn how to calculate the value of nPr using C Programming language.

C Program To Calculate The Value of nPr

nPr represents the probability of selecting an ordered set of ‘r’ objects from a group of ‘n’ number of objects. The order of objects matters in the case of permutation.

The formula to find the value of nPr is given by nPr = n! / (n – r)! where n is the total number of objects and r is the selected objects.

We will be using the above formula in our program to calculate the value of nPr.

So, without further ado, let’s begin this tutorial.

C Program To Calculate The Value of nPr

// C Program To Calculate The Value on nPr
#include <stdio.h>

int fact(int n){
    int i, a = 1;
    for (i = 1; i <= n; i++){
        a = a * i;
    }
    return a;
}

int main(){
    int n, r, npr;
    
    // Asking for Input
    printf("Enter the value of n: ");
    scanf("%d", &n);
    printf("Enter the value of p: ");
    scanf("%d", &r);
    
    npr = fact(n) / fact(n-r);
    printf("The Value of P(%d,%d) is %d.", n, r, npr);
    return 0;
}

Output

Enter the value of n: 5
Enter the value of p: 3
The Value of P(5,3) is 60.

How Does This Program Work ?

int fact(int n){
    int i, a = 1;
    for (i = 1; i <= n; i++){
        a = a * i;
    }

We have written a custom function which returns the factorial of a number.

    int n, r, npr;

In this program, we have declared three int data type variables named as n, r and npr.

    // Asking for Input
    printf("Enter the value of n: ");
    scanf("%d", &n);
    printf("Enter the value of p: ");
    scanf("%d", &r);

Then, the user is asked to enter the value of n and r.

    npr = fact(n) / fact(n-r);
    printf("The Value of P(%d,%d) is %d.", n, r, npr);

Finally, the nPr is calculated using the formula n! / (n – r)! And printed to the screen using printf() function.

Conclusion

I hope after going through this post, you understand how to calculate the value of nPr using C Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

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