Design a class to overload a function series() as follows: (a) void series(int x, int n) - to display the sum of the series given below: x^1 + x^2 + x^3 + ... to n terms (b) void series(int p) - to display the following series: 0, 7, 26, 63, ... to p terms (c) void series() - to display the sum of the series: 1/2 + 1/3 + 1/4 + ... + 1/10
Topic: Method overloading — three series
Answer
class SeriesOverload { void series(int x, int n) { double sum = 0.0; for(int i = 1; i <= n; i++) sum = sum + Math.pow(x, i); System.out.println("Sum of the series = " + sum); }
void series(int p) { for(int i = 1; i <= p; i++) System.out.print((i * i * i - 1) + " "); System.out.println(); }
void series() { double sum = 0.0; for(int i = 2; i <= 10; i++) sum = sum + 1.0 / i; System.out.println("Sum = " + sum); }
public static void main(String args[]) { SeriesOverload ob = new SeriesOverload(); ob.series(2, 4); ob.series(4); ob.series(); } }
Three methods named series(), told apart by their parameter lists — (int, int), (int) and none at all.
Part (a): each term is x raised to the term number, so Math.pow(x, i) inside a loop from 1 to n. The sum is declared double because pow() returns a double and the total can grow large.
Part (b) is the one that needs thought. Look for the rule behind 0, 7, 26, 63: they are 1-1, 8-1, 27-1, 64-1 — that is, i^3 - 1 for i = 1, 2, 3, 4. Finding the pattern is the real work; the code that follows is one line. Whenever a series is given by its first few terms, test squares and cubes with a small offset first.
Part (c): the terms are 1/2 to 1/10, so the loop runs from 2 to 10 and adds 1.0 / i. Write 1.0 and NOT 1 — with two ints, 1/i would be integer division and every term would come out as 0, making the sum 0.0. That single decimal point is where the marks are won or lost.
x, n int - the base and the number of terms of the first series p int - number of terms of the second series i int - loop variable sum double - running total of the series ob SeriesOverload - object used to invoke the methods