Computer Applications
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
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
Related Questions
Method prototype for the method compute which accepts two integer arguments and returns true/false.
- void compute (int a, int b)
- boolean compute (int a, int b)
- Boolean compute (int a,b)
- int compute (int a, int b)
Assertion (A): An argument is a value that is passed to a method when it is called.
Reason (R): Variables which are declared in a method prototype to receive values are called actual parameters
- Both Assertion (A) and Reason (R) are true and Reason (R) is a correct explanation of Assertion (A)
- Both Assertion (A) and Reason (R) are true and Reason (R) is not a correct explanation of Assertion(A)
- Assertion (A) is true and Reason (R) is false
- Assertion (A) is false and Reason (R) is true