PRASHNIKAप्रश्निका
Back to the paper

A super class Number is defined to calculate the factorial of a number. Define a sub class Series…

Computer Science20185 marksProgram
A super class Number is defined to calculate the factorial of a number. Define a sub class Series to find the sum of the series $S = 1! + 2! + 3! + 4! + \dots + n!$ The details of the members of both the classes are given below: Class name : Number Data member/instance variable: n : to store an integer number Member functions/methods: Number(int nn) : parameterized constructor to initialize the data member n=nn int factorial(int a) : returns the factorial of a number (factorial of $n = 1 \times 2 \times 3 \times \dots \times n$) void display( ) : displays the data members 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 super class Number has been defined. Using the concept of inheritance, specify the class Series giving the details of the constructor(…),void calsum( ) and void display( ). The super class, main function and algorithm need NOT be written.

Answer

Answer

AI
class Series extends Number
{
    long sum;

    Series(int nn)
    {
        super(nn);
        sum = 0;
    }

    void calsum()
    {
        sum = 0;
        for (int i = 1; i <= n; i++)
            sum = sum + factorial(i);
    }

    void display()
    {
        super.display();
        System.out.println("Sum of the series = " + sum);
    }
}
Explanation: the parameterised constructor Series(nn) passes nn up to the superclass Number's constructor via super(nn), which stores it in the inherited data member n, and initialises sum to 0. calsum() loops i from 1 to n and adds the inherited factorial(i) (i.e. i!) to sum on each iteration, computing $S = 1! + 2! + \dots + n!$. display() calls super.display() to reuse the superclass's printing of n, then prints sum. Tested (run for real, with a small Number superclass added only for testing purposes): for n=5, the program correctly computed sum = 1!+2!+3!+4!+5! = 1+2+6+24+120 = 153.
Inheritance, Interfaces and Polymorphism

From ISC 2018 Computer Science Paper 1, question 10.