KnowledgeBoat Logo

Computer Applications

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

  1. double series(double n) with one double argument and returns the sum of the series.
    sum = (1/1) + (1/2) + (1/3) + ………. + (1/n)
  2. double series(double a, double n) with two double arguments and returns the sum of the series.
    sum = (1/a2) + (4/a5) + (7/a8) + (10/a11) + ………. to n terms

Java

User Defined Methods

ICSE 2013

214 Likes

Answer

public class KboatSeries
{
    double series(double n) {
        double sum = 0;
        for (int i = 1; i <= n; i++) {
            double term = 1.0 / i;
            sum += term;
        }
        return sum;
    }
    
    double series(double a, double n) {
        double sum = 0;
        int x = 1;
        for (int i = 1; i <= n; i++) {
            int e = x + 1;
            double term = x / Math.pow(a, e);
            sum += term;
            x += 3;
        }
        return sum;
    }
    
    public static void main(String args[]) {
        KboatSeries obj = new KboatSeries();
        System.out.println("First series sum = " + obj.series(5));
        System.out.println("Second series sum = " + obj.series(3, 8));
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Design a class to overload a function series( ) as follows: (a) double series(double n) with one double argument and returns the sum of the series. sum = (1/1) + (1/2) + (1/3) + ………. + (1/n) (b) double series(double a, double n) with two double arguments and returns the sum of the series. sum = (1/a 2 ) + (4/a 5 ) + (7/a 8 ) + (10/a 11 ) + ………. to n terms

Answered By

58 Likes


Related Questions