plz calculate thr sum of the folowing series.....java program using while loop plzz or else just tell the logic..plzz tryna send thr code too plzx....thanks
Answers
Series Sum - Java
Question
Calculate the sum of the following series using a Java program, upto n terms.
Answer
We start by creating a Scanner object to take user input. We provide the user with a choice. Once a series is chosen from the menu, we employ the switch construct of Java.
For each series, the can be written down as follows:
For the alternate negative signs, we use the powers of -1. In Java, we use the method to get the exponents.
We initialize a Sum variable to 0. Then, we add each of the n terms to it and finally display the Sum.
Program Code: BrainlySeriesSum.java
import java.util.Scanner;
public class BrainlySeriesSum {
public static void main(String[] args) {
// Create Scanner object
Scanner sc = new Scanner(System.in);
// Menu
System.out.println("---Series Sum Menu---");
System.out.println("1. S = x + x^2 + x^3... upto n terms");
System.out.println("2. S = x - x^2 + x^3... upto n terms");
System.out.println("3. S = a - 2a + 3a - 4a ... upto n terms");
// Take user input of choice
System.out.print("\nEnter your choice [1/2/3]: ");
String choice = sc.next();
int n; // Number of terms
double Sum = 0; // Initialize Sum to 0
double x = 0;
double a = 0;
// Begin Switch Construct
switch(choice) {
case "1":
System.out.print("Enter value of x: ");
x = sc.nextDouble();
System.out.print("Enter value of n: ");
n = sc.nextInt();
for(int i = 1; i <= n; i++) {
Sum += Math.pow(x, i); // x + x^2 + x^3 + ...
}
System.out.println("Sum = "+Sum);
break;
case "2":
System.out.print("Enter value of x: ");
x = sc.nextDouble();
System.out.print("Enter value of n: ");
n = sc.nextInt();
Sum = 0;
for(int i = 1; i <= n; i++) {
Sum += Math.pow(-1, i + 1) * Math.pow(x, i); // x - x^2 + x^3 + ...
}
System.out.println("Sum = "+Sum);
break;
case "3":
System.out.print("Enter value of a: ");
a = sc.nextDouble();
System.out.print("Enter value of n: ");
n = sc.nextInt();
Sum = 0;
for(int i = 1; i <= n; i++) {
Sum += Math.pow(-1, i + 1) * (i * a); // a - 2a + 3a - ...
}
System.out.println("Sum = "+Sum);
break;
default:
System.out.println("Invalid choice");
}
sc.close();
}
}