Java program to calculate the value of nCr

Given the values of N and R, we have to calculate the value of nCr.
Submitted by Nidhi, on February 28, 2022

Problem Solution:

nCr: nCr is known as a combination, which is the method of selection of 'r' objects from a set of 'n' objects where the order of selection does not matter.

To find the value of nCr, we use the formula: nCr = n!/[r!( n-r)!]

Program/Source Code:

The source code to calculate the value of nCr is given below. The given program is compiled and executed successfully.

// Java program to calculate the 
// value of nCr

import java.util.Scanner;

public class Main {
  static 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;
  }

  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int n = 0;
    int r = 0;

    int nCr = 0;

    System.out.printf("Enter the value of N: ");
    n = SC.nextInt();

    System.out.printf("Enter the value of R: ");
    r = SC.nextInt();

    nCr = getFactorial(n) / (getFactorial(r) * getFactorial(n - r));

    System.out.printf("The nCr is: %d\n", nCr);
  }
}

Output:

Enter the value of N: 7
Enter the value of R: 5
The nCr is: 21

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains two static methods getFactorial() and main().

The getFactorial() method is used to calculate the factorial of the given number.

The main() method is an entry point for the program. Here, we read values N, R  from the user using the Scanner class. Then we calculated the nCr and printed the result.

Java Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






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