Sum of Numbers

Page 1 of 1

3 Replies - 1855 Views - Last Post: 18 October 2009 - 01:55 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=132816&amp;s=5d835aced4d7621a51c5c21d0df5cd24&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 pennstatelions

Reputation: 0
• Posts: 13
• Joined: 05-October 09

Sum of Numbers

Posted 18 October 2009 - 01:33 PM

Write a code that will ask the user for a number and then sum the numbers from 1 to the number inputted by the user. Use a while loop in your code.

I'm really not sure how to do the part about adding the numbers from 1 to the number provided. So far I have:
```Scanner input= new Scanner (System.in);
System.out.print("Enter an integer");
int x= input.nextInt();
int sum=1;
while (x>=1){
sumt += x;
x++;
}

```

I feel like I was on the right track until the "sumt" part..

Is This A Good Question/Topic? 0

Replies To: Sum of Numbers

#2 erik.price

• D.I.C Lover

Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

Re: Sum of Numbers

Posted 18 October 2009 - 01:40 PM

Try a for loop instead. You could use a while loop, but a for would be more convienent.

```int sum = 0;
for(int i=1; i <= x; i++)
{
sum += i;
}

```

Correct me if that's not what you're looking for.

EDIT 2: didn't see the "use a while loop" part. check out Martyr2's post for how to do it that way

This post has been edited by erik.price: 18 October 2009 - 01:44 PM

#4 Martyr2

• Programming Theoretician

Reputation: 5205
• Posts: 13,951
• Joined: 18-April 07

Re: Sum of Numbers

Posted 18 October 2009 - 01:41 PM

You are close...

```Scanner input= new Scanner (System.in);
System.out.print("Enter an integer");
int x= input.nextInt();

int sum=0;
int count = 1;

// Loop from 1 to the number they entered
while (count <= x){
// Accumulate in sum
sum += x;
count++;
}

System.out.println("Sum is: " + sum);

```

We setup a counter to go from 1 to the number they entered, each time through the loop adding the value of x onto sum.

This post has been edited by Martyr2: 18 October 2009 - 01:42 PM

#5 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12298
• Posts: 45,399
• Joined: 27-December 08

Re: Sum of Numbers

Posted 18 October 2009 - 01:55 PM

I may be missing something, but this just sounds like multiplication. Try this:
```product = x * n; //x is the number, n is the number of times to add

```