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);
}
}
Re: Sum of series program logical error
What does it do instead? Do you have a question?
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