How to sum a series with the last term being the denominator of user input in Java [closed]

0 votes
asked Sep 12, 2017 by fgdark

In the series: 1/3 + 3/5 + 5/7 + 7/9 + 9/11 +.........#/nth, I am trying to make the nth the denominator of a series such as if the user inputted 5 it would compute 1/3 + 3/5, 5 being the last term which the user inputted. I was able to make the code compute the number of terms such as 5 would compute 5 terms 1/3 + 3/5 + 5/7+ 7/9 + 9/11 . here is my code:

import java.util.Scanner;
public class n01092281
{
//for loop that computes a sum of the series
    public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.println("Enter your nth term for the series.");
      double userInput = input.nextInt();   
      double sum = 0.0;
      for(int i = 2; i <= userInput*2; i+=2) {
        sum += ((double)(i-1)/(i+1));
       }
  }
}

1 Answer

0 votes
answered Sep 12, 2017 by awais-syed

The problem is with your for loop conditions. You are looping it for userInput*2 times. Subtract it by 2 and initialize i to 1 since your series starts with 1 as numerator.

import java.util.Scanner;

public class n01092281 {
    //for loop that computes a sum of the series
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter your nth term for the series.");
        double userInput = input.nextInt();
        double sum = 0.0;
        for (double i = 1; i <= userInput - 2; i += 2) {
            sum += (i / (i + 2));
        }
        System.out.println(sum);
    }
}
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...