C# program to calculate the NCR

Here, we are going to learn how to calculate the NCR in C#?
Submitted by Nidhi, on October 11, 2020

Here we will calculate the NCR using the below formula.

NCR =  n!/(r!)*(n-r)! ;

Program:

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

//C# program to calculate the NCR.

using System;

class Ncr
{
    static int CalculateFactorial(int num)
    {
        int fact = 1;

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

        return fact;
    }

    static int CalculateNcr(int n, int r)
    {
        int ncr = 0;
        int fact1 = 0;
        int fact2 = 0;
        int fact3 = 0;

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

        ncr = fact1 / (fact2*fact3);

        return ncr;
    }
    static void Main(string[] args)
    {
        int ncr = 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());

        ncr = CalculateNcr(n, r);

        Console.WriteLine("Ncr: " + ncr);
    }
}

Output:

Enter the value of 'n': 7
Enter the value of 'r': 5
Ncr: 21
Press any key to continue . . .

Explanation:

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

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

The CalculateNcr() is used to calculate the Ncr using the below formula.

NCR =  n!/(r!)*(n-r)! ;

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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.