ICSE Class 10 Computer Applications
Question 35 of 69
Iterative Constructs in Java — Question 35
Back to all questions 35
Question Question 30(ii)
Write a program in Java to find the sum of the given series:
x1 - x2 + x3 - x4 + ..... - xn , where x = 3
import java.util.Scanner;
public class KboatSeries
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int x = 3;
double sum = 0;
for (int i = 1; i <= n; i++) {
double term = Math.pow(x, i);
if (i % 2 == 0)
sum -= term;
else
sum += term;
}
System.out.println("Sum = " + sum);
}
}Output
