×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to calculate the value of nPr

Here, we are going to learn how to calculate the value of nPr using C program?
Submitted by Nidhi, on August 11, 2021

Problem statement

Read the value of n and r and calculate the nPr.

nPr

The nPr is the permutation of arrangement of 'r' objects from a set of 'n' objects, into an order or sequence. The formula to find permutation is: nPr = (n!) / (n-r)!

C program to calculate the value of nPr

The source code to calculate the value of nPr is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to calculate the value of nPr

#include <stdio.h>

int getFactorial(int num)
{
    int f = 1;
    int i = 0;

    if (num == 0)
        return 1;

    for (i = 1; i <= num; i++)
        f = f * i;

    return f;
}

int main()
{
    int n = 0;
    int r = 0;

    int nPr = 0;

    printf("Enter the value of N: ");
    scanf("%d", &n);

    printf("Enter the value of R: ");
    scanf("%d", &r);

    nPr = getFactorial(n) / getFactorial(n - r);

    printf("The nPr is: %d\n", nPr);

    return 0;
}

Output

RUN 1:
Enter the value of N: 7
Enter the value of R: 3
The nPr is: 210

RUN 2:
Enter the value of N: 5
Enter the value of R: 0
The nPr is: 1

RUN 3:
Enter the value of N: 0
Enter the value of R: 5
The nPr is: 1

RUN 4:
Enter the value of N: 11
Enter the value of R: 5
The nPr is: 55440

Explanation

In the above program, we created two functions getFactorial(), main(). The getFactorial() function is used to find the factorial of the given number and return the result to the calling function.

In the main() function, we read the values of n and r. Then we calculate the nPr with the help of the getFactorial() function and print the result on the console screen.

C Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.