KnowledgeBoat Logo

Java Series Programs

Write a program in Java to find the sum of the following series:

S = a - (a/2!) + (a/3!) - (a/4!) + ……. to n

Java

Java Nested for Loops

ICSE

17 Likes

Answer

import java.util.Scanner;

public class KboatSeries
{
    public void computeSum() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a: ");
        int a = in.nextInt();
        System.out.print("Enter n: ");
        int n = in.nextInt();
        double sum = 0;
        
        for (int i = 1; i <= n; i++) {
            double f = 1;
            for (int j = 1; j <= i; j++) {
                f *= j;
            }
            if (i % 2 == 0)
                sum -= a / f;
            else
                sum += a / f;
        }
        System.out.println("Sum=" + sum);
        
    }
}

Output

BlueJ output of Write a program in Java to find the sum of the following series: S = a - (a/2!) + (a/3!) - (a/4!) + ……. to n

Answered By

11 Likes