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.
Program:
The source code to calculate the NCR is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
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.
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.