KnowledgeBoat Logo

Computer Applications

Using switch statement, write a menu driven program for the following:

(a) To find and display the sum of the series given below:

S = x1 - x2 + x3 - x4 + x5 - ………………….. - x20

(b) To find and display the sum of the series given below:

S = 1a2+1a4+1a6+1a8+\dfrac{1}{\text{a}^2} + \dfrac{1}{\text{a}^4} + \dfrac{1}{\text{a}^6} + \dfrac{1}{\text{a}^8} + ………………….. to n terms

For an incorrect option, an appropriate error message should be displayed.

Java

Java Iterative Stmts

ICSE

5 Likes

Answer

import java.util.Scanner;

public class KboatSeriesSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Sum of x^1 - x^2 + .... - x^20");
        System.out.println("2. Sum of 1/a^2 + 1/a^4 + .... to n terms");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();
        
        switch (ch) {
            case 1:
                System.out.print("Enter the value of x: ");
                int x = in.nextInt();
                long sum1 = 0;
                for (int i = 1; i <= 20; i++) {
                    int term = (int)Math.pow(x, i);
                    if (i % 2 == 0)
                        sum1 -= term;
                    else
                        sum1 += term;
                }
                System.out.println("Sum = " + sum1);
                break;

            case 2:
                System.out.print("Enter the number of terms: ");
                int n = in.nextInt();
                System.out.print("Enter the value of a: ");
                int a = in.nextInt();
                int c = 2;
                double sum2 = 0;
                for(int i = 1; i <= n; i++)  {                   
                    sum2 += (1/Math.pow(a, c));
                    c += 2;
                }                     
                System.out.println("Sum = " + sum2);
                break;

            default:
            System.out.println("Incorrect choice");
            break;
        }
    }
}

Output

BlueJ output of Using switch statement, write a menu driven program for the following: (a) To find and display the sum of the series given below: S = x 1 - x 2 + x 3 - x 4 + x 5 - ………………….. - x 20 (b) To find and display the sum of the series given below: S = ………………….. to n terms For an incorrect option, an appropriate error message should be displayed.BlueJ output of Using switch statement, write a menu driven program for the following: (a) To find and display the sum of the series given below: S = x 1 - x 2 + x 3 - x 4 + x 5 - ………………….. - x 20 (b) To find and display the sum of the series given below: S = ………………….. to n terms For an incorrect option, an appropriate error message should be displayed.

Answered By

3 Likes


Related Questions