# Sum of series program logical error

Printable View

• August 12th, 2011, 10:07 AM
Neel0075
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);
}
}
• August 12th, 2011, 10:23 AM
KevinWorkman
Re: Sum of series program logical error
What does it do instead? Do you have a question?
• August 12th, 2011, 11:26 AM
Johannes
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.

Code java:

``` 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