- Home
- Java Series Programs
Write the program to find the sum of the following series
Java Series Programs
Write the program to find the sum of the following series:
S = a - a3 + a5 - a7 + ……. to n
Answer
import java.util.Scanner;
public class KboatSeries
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
int a = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0;
for (int i = 1, j = 1; i <= n; i = i + 2, j++) {
if (j % 2 == 0)
sum -= Math.pow(a, i);
else
sum += Math.pow(a, i);
}
System.out.println("Sum=" + sum);
}
}