Series Sum ISC 2014 Theory

A class SeriesSum is designed to calculate the sum of the following series:
Sum = x2 / 1! + x4 / 3! + x6 / 5! + … + xn / (n – 1)!

Some of the members of the class are given below:
Class name: SeriesSum
Data members/instance variables:
x: to store an integer number.
n: to store number of terms.
sum: double variable to store the sum of the series.
Member functions:
SeriesSum(int xx, int nn): constructor to assign x = xx and n = nn.
double findFact(int m): to return the factorial of m using recursive technique.
double findPower(int x, int y): to return x raised to the power of y using recursive technique.
void calculate(): to calculate the sum of the series by invoking the recursive functions respectively.
void display(): to display the sum of the series.

(a) Specify the class SeriesSum, giving details of the constructor, double findFact(int), double findPower(int, int), void calculate() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.

(b) State the two differences between iteration and recursion.

import java.io.*;
class SeriesSum{
    private int x;
    private int n;
    private double sum;
    public SeriesSum(int xx, int nn){
        x = xx;
        n = nn;
        sum = 0.0;
    }
    public double findFact(int m){
        if(m <= 1)
            return 1.0;
        else
            return m * findFact(m - 1);
    }
    public double findPower(int x, int y){
        if(y == 0)
            return 1.0;
        else
            return x * findPower(x, y - 1);
    }
    public void calculate(){
        for(int i = 1; i <= n; i++)
            sum += findPower(x, i * 2) / findFact(i * 2 - 1);
    }
    public void display(){
        System.out.println("Sum = " + sum);
    }
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("x = ");
        int xx = Integer.parseInt(br.readLine());
        System.out.print("n = ");
        int nn = Integer.parseInt(br.readLine());
        SeriesSum obj = new SeriesSum(xx, nn);
        obj.calculate();
        obj.display();
    }
}

Two differences between iteration and recursion:
a) When a loop repeats, it uses the same memory locations. But in recursion, fresh memory space is allocated each time.
b) Recursion is slower and uses more memory space when compared with loops.

Leave a Reply

%d bloggers like this: