Design a class to overload a function series( ) as follows:
Java Programming Language (Article) (Program)
147
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:
x1 + x2 + x3 + .......... xn terms
(b) void series (int p) – To display the following series:
0, 7, 26, 63 .......... p terms
(c) void series () – To display the sum of the series given below:
1/2 + 1/3 + 1/4 + .......... 1/10
Program:
public class RansariOverloadSeries { // Overloaded method to calculate the sum of powers of x up to n void series(int x, int n) { long sum = 0; for (int i = 1; i <= n; i++) { sum += Math.pow(x, i); } System.out.println("Sum = " + sum); } // Overloaded method to print the first p terms of the sequence i^3 - 1 void series(int p) { for (int i = 1; i <= p; i++) { int term = (int) (Math.pow(i, 3) - 1); System.out.print(term + " "); } System.out.println(); } // Overloaded method to calculate the sum of a harmonic series from 1/2 to 1/10 void series() { double sum = 0.0; for (int i = 2; i <= 10; i++) { sum += 1.0 / i; } System.out.println("Sum = " + sum); } } // Main class to test the RansariOverloadSeries methods class Main { public static void main(String[] args) { // Create an object of RansariOverloadSeries RansariOverloadSeries series = new RansariOverloadSeries(); // Test the method: series(int x, int n) System.out.println("Testing series(int x, int n):"); series.series(2, 5); // Example: x = 2, n = 5 // Test the method: series(int p) System.out.println("Testing series(int p):"); series.series(5); // Example: p = 5 // Test the method: series() System.out.println("Testing series():"); series.series(); } }
Output:
Testing series(int x, int n): Sum = 62 Testing series(int p): 0 7 26 63 124 Testing series(): Sum = 1.9277777777777778
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.