View Full Version : Display sum of consecutive numbers
onedollartotown
02-10-2009, 07:41 AM
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
servlet
02-10-2009, 08:43 AM
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.
onedollartotown
02-10-2009, 10:20 AM
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.
servlet
02-10-2009, 10:50 AM
Here's the 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
Old Pedant
02-11-2009, 02:26 AM
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:
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:
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.)
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.