ISC computer science paper 2018 Question 10 solved
A superclass Number is defined to calculate the
factorial of a number. Define a subclass Series to find the sum of the series S
= 1! + 2! + 3! + 4! + ………. + n!.
The details of the members of both classes are
given below:
Class name: Number
Data member/instance variable:
n: to store an integer number
Member functions/methods:
Number(): constructor to initialize the data member
int factorial(int a): returns the factorial of
a number
(factorial of n = 1 × 2 × 3 × …… × n)
void display()
Class name: Series
Data member/instance variable:
sum: to store the sum of the series
Member functions/methods:
Series(…) : parameterized constructor to
initialize the data members of both the classes
void calSum(): calculates the sum of the given
series
void display(): displays the data members of both
the classes
Assume that the superclass Number has been
defined. Using the concept of inheritance, specify the class Series giving the
details of the constructor (…), void caSum(), and void display().
The superclass, main function, and algorithm need
NOT be written.
Solution with explanation
In the following program, we provide class Number
as in the question with a parameterize constructor and factorial(int num)
method where factorial is calculated.
public class Number
{
int
i, f, nn, number; // Instance variables of Base class
public Number(int n)
{
nn = n; // initailize with the
inputed value
}
// factorial() method with parameter
public int factorial(int num)
{
number = num;
f=1;
for(i=1; i<=number; i++)
{
f = f * i; // factorial calculation
}
return f;
}
//
display() method with
public void display()
{
System.out.println("Number:" + nn);
}
}
In the following class, Series extends the base
class Number. In the drive class, we provide a parameterize constructor Series (int
n) and calcSum() method which calculate the summation of factorials.
class Series extends Number
{
int
sum; // Instance Variable
//
Series constructor
public Series(int n)
{
super(n);
sum = 0;
}
//
calculation of factorial in sum variable
//
with factorial() method from base class
public void calcSum()
{
for(int i = 1; i <= nn; i++)
{
sum = sum + super.factorial(i);
}
}
//
drive class display method
public void display()
{
super.display();
System.out.println("Series sum:" + sum);
}
}
In the following source code, we provide Test
class for inputting the value and to print the calculated values of the sum.
import java.util.*;
class Test
{
public static void main(String args[ ])
{
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
n
= sc.nextInt();
Series obj = new Series(n);
obj.calcSum();
obj.display();
}
}
Output:
Enter the number: 5
Number:5
Series sum:153
More Java program