KnowledgeBoat Logo

Java Series Programs

Design a class to overload a function series( ) as follows:

(a) void series(int a, int n) — To display the sum of the series given below:

a - (a/2!) + (a/3!) - (a/4!) + …… n terms

(b) void series(int n) — To display the sum of the series given below:

1/2 - 2/3 + 3/4 - 4/5 + …… n terms

Write a main method to create an object and invoke the above methods.

Java

User Defined Methods

ICSE

19 Likes

Answer

import java.util.Scanner;

public class KboatOverload
{
    void series(int a, int n) {
        double sum = 0;
        int m = 1;
        for (int i = 1; i <= n; i++) {
            long f = 1;
            for (int j = 1; j <= i; j++) {
                f *= j;
            }
            double t = (double)a / f * m;
            sum += t;
            m *= -1;
        }
        System.out.println("Series Sum = " + sum);
    }
    
    void series(int n) {
        double sum = 0;
        int m = 1;
        for (int i = 1; i <= n; i++) {
            double t = ((double)i / (i + 1)) * m;
            sum += t;
            m *= -1;
        }
        System.out.println("Series Sum = " + sum);
    }
    
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a: ");
        int a = in.nextInt();
        System.out.print("Enter n: ");
        int n = in.nextInt();
        
        KboatOverload obj = new KboatOverload();
        obj.series(a, n);
        obj.series(n);
    }
}

Output

BlueJ output of Design a class to overload a function series( ) as follows: (a) void series(int a, int n) — To display the sum of the series given below: a - (a/2!) + (a/3!) - (a/4!) + …… n terms (b) void series(int n) — To display the sum of the series given below: 1/2 - 2/3 + 3/4 - 4/5 + …… n terms Write a main method to create an object and invoke the above methods.

Answered By

2 Likes