C# program to calculate the nPr

Here, we are going to learn how to calculate the NPR in C#? By Nidhi Last updated : April 15, 2023

nPr Formula

Here, we will calculate the NPR using the below formula.

NPR =  n!/(n-r)!;

C# code to calculate the nPr

The source code to calculate the NPR is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to calculate the nPr.

using System; 

class Npr
{
    static int CalculateFactorial(int n)
    {
        int fact =1;

        for (int i = 2; i <= n; i++)
        {
            fact = fact * i;
        }

        return fact;
    }

    static int CalculateNpr(int n, int r)
    {
        int npr     = 0;
        int fact1   = 0;
        int fact2   = 0;

        fact1 = CalculateFactorial(n);
        fact2 = CalculateFactorial(n - r);

        npr = fact1 / fact2;

        return npr;
    }
    static void Main(string[] args)
    {
        int npr  = 0;
        int n  = 0;
        int r  = 0;

        Console.Write("Enter the value of 'n': "); 
        n = int.Parse(Console.ReadLine());

        Console.Write("Enter the value of 'r': ");
        r = int.Parse(Console.ReadLine());
        
        npr = CalculateNpr(n, r);

        Console.WriteLine("Npr: "+npr);
    }
}

Output

Enter the value of 'n': 10
Enter the value of 'r': 5
Npr: 30240
Press any key to continue . . .

Explanation

Here, we created a class Npr that contains three static methods CalculateFactorial(), CalculateNpr(), and Main() method.

The CalculateFactorial() is used to calculate the factorial of the specified factorial and return to the calling method.

The CalculateNpr() is used to calculate the Npr using the below formula.

NPR =  n!/(n-r)! ;

The Main() method is the entry point for the program, Here we read the value of n and r and called the CalculateNpr() method that will return NPR that will be printed on the console screen.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





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