KnowledgeBoat Logo

Java Series Programs

Write a program in Java to input the values of x and n and print the sum of the following series:

S = 1 - x2/2! + x4/4! - x6/6! + ……. xn/n!

Java

Java Nested for Loops

8 Likes

Answer

import java.util.Scanner;

public class KboatSeries
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter x: ");
        int x = in.nextInt();
        System.out.print("Enter n: ");
        int n = in.nextInt();
        
        if (n % 2 != 0) {
            System.out.println("n should be even");
            return;
        }
        
        double sum = 0;
        int a = 1;
        for (int i = 0; i <= n; i += 2) {
            long f = 1;
            for (int j = 1; j <= i; j++) {
                f *= j;
            }
            double t = Math.pow(x, i) / f * a;
            sum += t;
            a *= -1;
        }
        
        System.out.println("Sum = " + sum);
    }
}

Output

BlueJ output of Write a program in Java to input the values of x and n and print the sum of the following series: S = 1 - x 2 /2! + x 4 /4! - x 6 /6! + ……. x n /n!

Answered By

2 Likes