Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to calculate nCr and 1!+2!+3!+4! using inheritance. FORMULA: nCr = n!/(r!*(n-r)!)

Java Code Example — Inheritance Programs

ADVERTISEMENT

Java Program to calculate nCr and 1!+2!+3!+4! using inheritance. FORMULA: nCr = n!/(r!*(n-r)!)

Objective

Write a Java program to demonstrate Hierarchical Inheritance by calculating both nCr and a factorial series.

Algorithm / Approach

  1. Create a base class Factorial with a method fact(x) to calculate factorials.
  2. Create a class SeriesA that extends Factorial to calculate nCr using the inherited fact() method.
  3. Create another class SeriesB that also extends Factorial to calculate the sum of factorials.
  4. In main, instantiate both child classes independently and execute their respective calculations.
Factorial.java
import java.util.Scanner;
class Factorial {
 Scanner s=new Scanner(System.in);
 int fact(int x) {
  int res = 1;
  for(int i=1; i<= x; i++) {
   res = res * i;
  }
 return res;
 }
}
class SeriesA extends Factorial{
 public void calculate() {
  System.out.print("Enter N: ");
  int n = s.nextInt();
  System.out.print("Enter R: ");
  int r = s.nextInt();
  int res=fact(n)/(fact(n-r)*fact(r));
  System.out.println("Result- "+res);
 }
}
class SeriesB extends Factorial {
 public void show() {
  System.out.print("Enter N: ");
  int n = s.nextInt();
  int sum =0;
  for(int i=1; i<=n; i++) {
   sum = sum+fact(i);
  }
  System.out.print("Result- "+sum);
 }
}
class Main{
 public static void main(String[] a)
 {
  SeriesA s = new SeriesA();
  s.calculate();
  SeriesB s2 = new SeriesB();
  s2.show();
 }
}

Expected Output

Enter N: 5
Enter R: 3
Result- 10
Enter N: 5
Result- 153

Explanation of the Program

  • Hierarchical inheritance occurs when multiple derived classes inherit from a single base class.
  • In this program, calculating both nCr and factorial sums requires repeatedly calculating factorials. Instead of writing the factorial logic twice, we place it in a common parent class.
  • Both SeriesA and SeriesB can now share this utility method without repeating code.

Complexity

Time Complexity O(n) - Dominated by the factorial loops.
Space Complexity O(1)
ADVERTISEMENT