icse-promo

Question

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

i) To find and display the sum of the series given below:
S = x1 – x2 + x3 – x4 + x5 … – x20
(where x=2)

ii) To display the following series:
1 11 111 1111 11111
For an incorrect option, an appropriate error message should be displayed.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;

public class program6
{
	public static void main(String[] args)
	{
	    int choice=0,i=0,j=0;
	    double sum=0;
	    System.out.println("Press 1 for Sum of series");
	    System.out.println("Press 2 to Display Series");
            System.out.print("Enter your choice: ");
	    Scanner sc = new Scanner(System.in);
	    choice = sc.nextInt();
	    switch (choice)
	    {
		    case 1:
                    sum = 0;
                    for (i = 1; i <= 20; i++)
                    {
                        if (i % 2 == 0)
                        {
                            sum = sum - Math.pow(2, i);
                        }
                        else
                        {
                            sum = sum +Math.pow(2, i);
                        }
                    }
                    System.out.println("Sum = " + sum);
                    break;
		    case 2:
		        int temp =0;
		        for (i = 1; i<= 5; i++)
		        {
			        temp=temp*10+1;
			        System.out.print(temp+" ");
		        
		        }
		        break;
		    default:
		        System.out.println("Invalid choice");
		        break;
	    }
    }
}

				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *