Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Display sum of consecutive numbers

1. ## Display sum of consecutive numbers

Hi Guys,

I need your help on while statements.

Currently i have this:-

public class Numbers
{
public static void main(String[] args)
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);

while ( x <= y)
{
System.out.println( x );
x = x + 1;
}
}
}

How do I modify the code above to include display of sum of the consecutive numbers using while statement? Thanks.

Regards,
John

• I really don't understand what you mean by 'display of sum of the consecutive numbers'.
Can you post, what output do you expect, with an example, then I may be able to help you.

• Hi Servlet,

Lets say i enter x = 1 and y = 5. It will display the numbers 1,2,3,4,5 and add up all these numbers which would be 15 (sum of consecutive numbers).

I need it using while statement.

• Here's the code

Code:
```public class ConsecutiveNumberCalculator {

public static void main(String[] args) {
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int total = 0;

while (x <= y) {
System.out.print(x + " ");
total += x;
x = x + 1;
}
System.out.println(" = " + total);
}

}```
It will output 1 2 3 4 5 6 = 21

• Of course, if you don't *HAVE* to display the sequence of integers--if you really only need the first and last numbers displayed along with the sum--then a bit of algebra will simplify the code:
Code:
```public class SumConsecutiveNumbers
{
public static void main(String[] args)
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
if ( y < x ) /* would be a good idea to do this no matter what code is used */
{
x = y;
y = Integer.parseInt(args[0]);
}
System.out.println("The sum of " + x + " through " + y + " is " +  ((x+y)*y)/2 );
}

}```
Hmmm....come to think of it, *THIS* code does *NOT* need to do the swap on x and y if you code it thus:
Code:
```public class SumConsecutiveNumbers
{
public static void main(String[] args)
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
System.out.println("The sum of " + x + " through " + y + " is "
+  ( ( x + y ) * ( x > y ? x : y ) / 2 );
}

}```
Sneaky enough? (Well, not quite...doesn't work if the range is a negative number through a positive number.)

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•