fgdark
fgdark

Reputation: 21

How to calculate the sum of a series with the nth term being user input in Java

I am trying to compute a summation and Pi. I have gotten the Pi calculation to work, but am having difficulty on the summation. The output of the summation is supposed to calculate 1/3 + 3/5 + 5/7 .... a number/n the nth term is the user input, but I am uncertain about my calculation. If I input 5 the output should calculate 1/3 + 3/5, but this code would add 5 terms 1/3 + 3/5 + 5/7 + 7/9 + 9/11, what am I doing wrong? Here is the code:

import java.util.Scanner;
public class n01092281
{
    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));
       }
      System.out.printf("The sum of the series is %12.12f" , sum); 
      double Pi = 0;
      for (int counter = 1; counter < userInput; counter++){
         Pi += 4 * (Math.pow(-1,counter + 1)/((2*counter) - 1));
      }
      System.out.printf(" ,The computation of Pi is %1.12f",  Pi);
   }   
}

Upvotes: 0

Views: 1031

Answers (2)

According to your question your series is r/n where n is the nth term. Use this simple function to sum the series up to nth term.

private static void sum_up_series(int nth) {
    double sum = 0;
    for (int i = 0; i < nth; i++) {
        int r = (1 + (i * 2));
        int n = (3 + (i * 2));
        if (n <= nth) {
            sum += (double) (r) / (n);
            System.out.print(r + "/" + n + " ");
        }
    }
    System.out.print("\nsum = " + sum);
}

here is the output of n= 11

1/3 3/5 5/7 7/9 9/11 sum = 3.2435786435786436

Upvotes: 0

nagendra547
nagendra547

Reputation: 6302

I guess, you are doing the right calculation. I just changed the way you were using i. Also you just need to update the count how many times exactly you would like to go.

This is how I changed it

      double userInput = 11;
      int count =0;
      if(userInput>=3){
          count =(int)( userInput-1)/2;
      }
      double sum = 0.0;
      for(int i = 1; i <= count; i++) {
         sum += ((double)(2*i-1)/(2*i+1));
         System.out.print((2*i-1)+"/"+(2*i+1)+' ');
       }
      System.out.println();
      System.out.printf("The sum of the series is %12.12f" , sum); 

Output:-

1/3 3/5 5/7 7/9 9/11 
The sum of the series is 3.243578643579

Here I am also printing series, to make clear for you.

Upvotes: 1

Related Questions