Computer Science, asked by FIREBOY96, 3 months ago

Write a java program to print the sum of series

S = 2+4-6+8-10......nth term​

Answers

Answered by anindyaadhikari13
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:

  1. Accept the limit, say n.
  2. Initialise i=1,a=2,c=1,sum=0
  3. Iterate a loop n times.
  4. Add the value of a*c to sum.
  5. Increment the value of a by 2.
  6. Negate the value of c as each term is added and subtracted.
  7. Display the sum.

Refer to the attachment.

Attachments:
Answered by kamalrajatjoshi94
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