Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Sum of series program logical error

1. ## Sum of series program logical error

This program is supposed to calculate:
S= 2! -4! +6! -8! …..n terms

public class Series7
{
int sum, i, term, j, prod;
public void main(int n)
{
sum = 0;
term=2;
prod = 1;
for (i=1;i<=n;i++)
{
for(j=term;j>1;j--)
prod *= j;

term += 2;
if(i%2==0)
sum -= prod;
else
sum += prod;

}
System.out.println("The sum is "+sum);
}
}

2. ## Re: Sum of series program logical error

What does it do instead? Do you have a question?

3. ## Re: Sum of series program logical error

You have a ton of problems with syntax but that aside your logic problems stems from messy seperation of what each loop does.

Outer loop: adds 2 to the term, adds the fac result to the output sum.
Inner loop: Fac'ing the term.

Im not sure you are fac'ing right. Try using recursion as it brings beautiful solution to fac'ing.

public void myFunc(int n){
int sum = 0;
int term = 2;

for (int i = 1; i <= n ; i++){
if(i % 2 == 0)
{
sum -= myFac(term);
} else {
sum += myFac(term);
}
term += 2;
}
System.out.println(sum);
}

Remember to use highlight tags, or you code is unreadable