Tuesday, March 23, 2010

2 - 4 + 6 - 8......20

import java.io.*;
public class twominusfourplussixminuseight
{
public static void main(String args[])
{ System.out.println("2-4+6-8...-20");
int a=1;
int s=0;
for(int i=2;i<=20;i+=2)
{
if(a%2!=0)
s+=i;
else
s-=i;
a++;
System.out.println(a+ " " +i+ " " +s);

}
System.out.println(s);

}
}

16 comments:

  1. the logic should be if (a%4!=0)then sum+=a

    ReplyDelete
  2. Just use one loop for (i=2; i <=20;i=i+4)
    s=s+(i-(i+2));
    This will work.

    ReplyDelete
  3. Replies
    1. OUTPUT

      2-4+6-8...-20
      2 2 2
      3 4 -2
      4 6 4
      5 8 -4
      6 10 6
      7 12 -6
      8 14 8
      9 16 -8
      10 18 10
      11 20 -10
      -10

      Delete
  4. the output instead of coming -10 is coming 6

    ReplyDelete
  5. 👍👍👍☺👍👍👍👍👍☺

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. public class Sum_Series
    {
    public static void main(String[] args) {

    int s = 0;

    for (int i = 2; i <= 20; i = i + 2) {

    if (i % 4 == 0) {

    s = s - i;

    } else {

    s = s + i;

    }

    }

    System.out.println("The sum of the series is: "+s);

    }
    }

    That's how you do it. Hope it helps :)

    ReplyDelete
    Replies
    1. I think the logic should be if(i%4==0) this will be the right answer.....

      Delete