Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find out nCrusing static method.Formula : nCr = n!/((n-r)!*r!)

Java Code Example — OOP Programs

ADVERTISEMENT

Java Program to find out nCrusing static method.Formula : nCr = n!/((n-r)!*r!)

Objective

Calculate mathematical combinations (nCr) using a static helper method.

Algorithm / Approach

  1. Define a static float fact(int x) method that calculates and returns the factorial of x.
  2. In the main method, read n and r from the user.
  3. Calculate the combination using the formula: fact(n) / (fact(n-r) * fact(r)).
  4. Print the final result.
Test.java
import java.util.Scanner;
class Test {
 public static float fact(int x) {
  int f = 1;
  for(int i = 1; i<=x; i++) {
   f = f*i;
  }
  return f;
 }
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter N: ");
  int n = s.nextInt();
  System.out.print("Enter R: ");
  int r = s.nextInt();
  float res=fact(n)/(fact(n-r)*fact(r));
  System.out.print("Result = "+res);
 }
}

Expected Output

Enter N: 5
Enter R: 3
Result = 10.0

Explanation of the Program

  • The static keyword allows a method to belong to the class itself, rather than to any specific object instance.
  • Because fact() is static, we can call it directly from the main method (which is also static) without having to create an object using new.
  • This is highly useful for utility or mathematical functions that don't rely on an object's state (like Math.pow).

Complexity

Time Complexity O(n) - Because factorial calculations loop up to n.
Space Complexity O(1)

Common Mistakes

  • Trying to call a non-static method directly from a static context like main, which results in a compilation error ("non-static method cannot be referenced from a static context").
ADVERTISEMENT