1.

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 + x2 – 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.

Answer»

import java.io.*; 

class SwitchStatement { 

public static void main(String argsQ) throws IOException { 

InputStreamReader reader = new InputStreamReader(System.in); 

BufferedReader input = new BufferedReader(reader); 

System.out.println(“l-Sum of Series:”); 

System.out.println(“2-Display Special Series:”); 

System.out.println(“Enter your choice:”); 

String n1 = input.readLine( ); 

int ch = Integer.parselnt(nl); 

System.out.println(“Enter Number of Terms String t = input.readLine(); 

int n = Integer.parselnt(t); 

switch (ch) { case 1: 

int sign = -1; 

double term = 0; 

double sum = 0; 

int x = 2; 

System.out.println(“Value of x: ” +x); 

System.out.println(“Number of terms: ” +n); 

sum + = x; // First term added here,

for (int i = 2; i < = n; i+ +){ 

term = sign * Math.pow(x,i); 

sum + = term; 

sign *= -1; 

System.out.println(“Sum of Series +sum); 

break; 

case 2 : 

int num; 

System.out.println(“Enter the number of terms: ”); 

String tm = input.readLine(); . 

num = Integer.parselnt(tm); 

int s = 0, c; for (c = 1; c < = num; c+ +){ 

s = s * 10 + 1; 

System.out.print(s + ” “); 

} break; 

}

}



Discussion

No Comment Found

Related InterviewSolutions