Q:

Java program to calculate the value of nCr

belongs to collection: Java Basic Programs

0

Java program to calculate the value of nCr

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

nCrnCr 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 NR  from the user using the Scanner class. Then we calculated the nCr and printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to calculate the value of nPr... >>
<< Java program to read coordinate points and determi...