Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 5 of 5

02102009, 07:41 AM #1
 Join Date
 Feb 2009
 Posts
 7
 Thanks
 2
 Thanked 0 Times in 0 Posts
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
02102009, 08:43 AM
#2
 Join Date
 Jan 2009
 Location
 india
 Posts
 145
 Thanks
 0
 Thanked 5 Times in 5 Posts
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.
02102009, 10:20 AM
#3
 Join Date
 Feb 2009
 Posts
 7
 Thanks
 2
 Thanked 0 Times in 0 Posts
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.
02102009, 10:50 AM
#4
 Join Date
 Jan 2009
 Location
 india
 Posts
 145
 Thanks
 0
 Thanked 5 Times in 5 Posts
Here's the code
It will output 1 2 3 4 5 6 = 21Code: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); } }
02112009, 02:26 AM
#5
Of course, if you don't *HAVE* to display the sequence of integersif you really only need the first and last numbers displayed along with the sumthen a bit of algebra will simplify the code:
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]); 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 ); } }
Sneaky enough? (Well, not quite...doesn't work if the range is a negative number through a positive number.)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 ); } }