# Sum of Numbers

Page 1 of 1

## 3 Replies - 1645 Views - Last Post: 18 October 2009 - 01:55 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=132816&amp;s=8686f2f7fb1c49047797d8c6dd5953f9&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: 485
• 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: 4734
• Posts: 12,911
• 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: 11312
• Posts: 42,611
• 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

```