Reputation: 33
I 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.
Upvotes: 2
Views: 1072
Reputation: 308743
I think simpler is better.
Encapsulating it in a function makes your code easier to test and use outside the main method.
/**
* @link https://stackoverflow.com/questions/58606895/series-with-fractions-in-java
*/
public class P64 {
public static void main(String[] args) {
int n = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
System.out.println(String.format("n: %5d sum: %10.5f", n, series(n)));
}
static double series(int n) {
int sign = 1;
double sum = 0.0;
for (int i = 1; i <= n; ++i) {
double x = 2.0*i;
double term = sign*x/(x+1.0);
sum += term;
sign *= -1;
}
return sum;
}
}
Upvotes: 0
Reputation: 16498
I would use a variable for the alternating +-
and take a step of two at each iteration:
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;
int sign = 1;
for (double i = 2; i <= n; i = i+2 ) {
sum = sum + (sign * (i/(i+1)));
sign = -sign;
}
System.out.println(sum);
}
Upvotes: 2
Reputation: 3862
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
Upvotes: 2
Reputation: 5868
I removed the preincrement/postincrement trickery and made the limit determine the number of terms added up.
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++)
{
double delta = (2*i)/(2*i+1);
if(i%2==0)
sum -= delta;
else
sum += delta;
}
System.out.println(sum);
}
}
Upvotes: 2