Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Iterative Constructs in Java

Chapter 9

Iterative Constructs in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Sum of Alternating Powers Series


30(ii). Write a program in Java to find the sum of the given series:

x1 - x2 + x3 - x4 + ..... - xn , where x = 3

Program Title: Sum of Alternating Powers Series

Here’s a Java program to compute the alternating series:

x1 − x2 + x3 − x4 + ⋯ ± xn

with x = 3.

public class AlternatingSeries {

    public static void main(String[] args) {

        int x = 3; // value of x

        int n = 5; // number of terms, can be changed

        int sign = 1; // to alternate + and -

        double sum = 0.0;

 

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

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

            sign *= -1; // alternate the sign

        }

 

        System.out.println("Sum of the series for x = " + x + " and n = " + n + " is: " + sum);

    }

}

Output

Sample Input / Output (n = 5)
Sum of the series for x = 3 and n = 5 is: 177.0

📝 Explanation

31 – 32 + 33 – 34 + 35 = 3 – 9 + 27 – 81 + 243 = 177

How It Works

  1. sign variable starts at +1
  2. For each term, multiply the power of x with sign
  3. Flip the sign using sign *= -1 to alternate between + and -
  4. Sum all terms to get the result