View Full Version : Display sum of consecutive numbers

onedollartotown

02-07-2009, 11:54 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? Thanks.

Regards,

John

imaginationac

02-09-2009, 04:58 AM

Do you mean the sum of x and y?

Simply,

public class Numbers {

public static void main(String[] args) {

int from = Integer.parseInt(args[0]),

to = Integer.parseInt(args[1]);

for (int i = from, total = 0; i < to; ++i)

System.out.println(x + ": " + (total = total + x));

}

}

daily jobs

02-09-2009, 01:29 PM

The whole concept of the project is so "Given a positive integer Target, in how many different ways can Target be expressed as a sum of consecutive positive integers?"... The user inputs the number in a test box and the result is displayed in a listbox.Example of needed process:

if Target = 63, there are six solutions:

3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11

6 + 7 + 8 + 9 + 10 + 11 + 12

8 + 9 + 10 + 11 + 12 + 13

20 + 21 + 22

31 + 32

63

JVposter

02-20-2009, 02:36 PM

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? Thanks.

Regards,

John

you need to be more explicit

angie555

03-11-2009, 02:31 AM

Hmm... for x = x + 1; you should just use x++;. It saves time. Other than that... I'm not sure what your Q is.

-♥Angie

HosHos

08-13-2009, 12:44 PM

if you mean you are having a serial of inputs and you want to get their sum;

after taking them from the user in an array

this is the operation:

public static sum (int[] a)

{

int sum=0;

for(int i=0;i<"array size";i++)

{

sum+=a[i];

System.out.println( sum );

}

}

Bhargav

01-23-2010, 05:28 AM

its quite simple...

public class Numbers

{

public static void main(String args[])

{

int x = Integer.parseInt(args[0]);

int y = Integer.parseInt(args[1]);

int sum=0;

while (x<=y)

{

sum+=x;

++x;

}

System.out.println("Sum of the consecutive numbers within "+x +"and" +y +"is: "+sum);

}

}

with regards

Bhargav

Bhargav

01-23-2010, 05:31 AM

@john

the above post is for the sum of all the consecutive numbers...

plss be clear..

do u want the sum of each 2 consecutive numbers or 3 consecutive numbers or...so.on..

thanks

Bhargav

Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.