Search code examples
javafractions

Series with fractions in java


Refer 4th series for better clarificationI need to use loop to find the sum of the following series:

(2/3)-(4/5)+(6/7)-(8/9)+......±n

I have to use for-loop only for this program. Refer the code to see what I've done:

import java.util.Scanner;
public class P64 {
    public static void main(String args[]) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the limit");
        double n=sc.nextDouble();
        double sum=0;
        for(double i=1;i<=n;i++) {
            if(i%2==0)
            sum=sum-(++i/i++);
            else
            sum=sum+(++i/i++);
        }
            System.out.println(sum);
    }
}

I have tried this out but the output is either 1 or 0.


Solution

  • You should use a separate variable for values as using same in loop and your series will make it complex so, try this:

    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the limit");
        double n=sc.nextDouble();
        double sum=0;
        double j=1;
        for(double i=1;i<=n;i++)
        {
            if(i%2==0)
                sum=sum-(++j/++j);
            else
                sum=sum+(++j/++j);
        }
        System.out.println(sum);
    }
    
    Input: 4
    Output: -0.16507936507936516