KnowledgeBoat Logo

Java Series Programs

Using switch statement write a menu driven program to overload a function series as follows:

(a) void series() — To find and display the sum of the following series:
    S = 2 - 4 + 6 - 8 + 10 ….. - 20

(b) void series(int n, int x) — To find and display the sum of the following series:
    S = (x2 / 1!) + (x4 / 3!) + (x6 / 5!) + ……. to n terms

Java

User Defined Methods

ICSE

18 Likes

Answer

import java.util.Scanner;

public class KboatSeries
{
    void series() {
        int sum = 0;
        int t = 1;
        for (int i = 2; i <= 20; i += 2) {
            sum += t * i;
            t *= -1;
        }
              
        System.out.println("Sum = " + sum);
    }
    
    void series(int n, int x) {
        double sum = 0;
        for (int i = 2; i <= 2 * n; i += 2) {
            long f = 1;
            for (int j = 1; j <= i - 1;  j++) {
                f *= j;
            }
            double t = Math.pow(x, i) / f;
            sum += t;
        }
        
        System.out.println("Sum = " + sum);
    }
    
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        KboatSeries obj = new KboatSeries();
        System.out.println("Enter 1 for Series 1");
        System.out.println("Enter 2 for Series 2");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();
        switch (ch) {
            case 1:
            obj.series();
            break;
            
            case 2:
            System.out.print("Enter x: ");
            int x = in.nextInt();
            System.out.print("Enter no. of terms(n): ");
            int n = in.nextInt();
            obj.series(n, x);
            break;
            
            default:
            System.out.println("Incorrect Choice");
        }
    }
}

Output

BlueJ output of Using switch statement write a menu driven program to overload a function series as follows: (a) void series() — To find and display the sum of the following series: S = 2 - 4 + 6 - 8 + 10 ….. - 20 (b) void series(int n, int x) — To find and display the sum of the following series: S = (x 2 / 1!) + (x 4 / 3!) + (x 6 / 5!) + ……. to n termsBlueJ output of Using switch statement write a menu driven program to overload a function series as follows: (a) void series() — To find and display the sum of the following series: S = 2 - 4 + 6 - 8 + 10 ….. - 20 (b) void series(int n, int x) — To find and display the sum of the following series: S = (x 2 / 1!) + (x 4 / 3!) + (x 6 / 5!) + ……. to n terms

Answered By

7 Likes