Write a java program to print the sum of series
S = 2+4-6+8-10......nth term
Answers
Answered by
0
Answer:
This is the required Java program for the question.
import java.util.*;
public class Sum {
public static void main(String args[]) {
int n,a=2,c=1,s=0,i;
Scanner sc=new Scanner(System.in);
System.out.print("Enter limit - ");
n=sc.nextInt();
for(i=1;i<=n;i++,a+=2,c*=-1)
s+=a*c;
System.out.println("Sum of the series is: "+s);
sc.close();
}
}
Algorithm:
- Accept the limit, say n.
- Initialise i=1,a=2,c=1,sum=0
- Iterate a loop n times.
- Add the value of a*c to sum.
- Increment the value of a by 2.
- Negate the value of c as each term is added and subtracted.
- Display the sum.
Refer to the attachment.
Attachments:
Answered by
1
Answer:
Program:-
import java.util.*;
public class Series
{
public static void main(String args[ ])
{
Scanner in=new Scanner(System.in);
int n,s=0,a,b=2;
System.out.println("Enter n means the limit");
n=in.nextInt();
for(a=1;a<=n;a++)
{
if(a%2==0)
s=s+b;
else
s=s-b;
b=b+2;
}
System.out.println("The sum of the given series="+s);
}
}
Similar questions