# Sum of numbers

• 10-30-2009
kenjiro310
Sum of numbers
The purpose of this program is to display the sums of all of the numbers from one to the input number. Example if i enter 5 i want it to add the numbers 1+2+3+4+5 = 15 or if i enter 225 it will add 1+2+.....225

Here is what i am working with

insert
Code:

```#include <iostream.h> void main() { int Number, Sum; Sum = 0; cout << "Enter a number: " << endl; cin >> Number; while (Number >= 0) { Sum = Sum + Number; cout << "Current Total " << Sum << endl; cout << "Enter a number: " << endl; cin >> Number; } cout << "The total is " << Sum << endl; }```
It works fine when i go in order 1+2+3+.....10 but it does not add all i need.

Any hints will help thanks in advance.
• 10-30-2009
King Mir
Instead of asking for a new number, you should be subtracting one from the number.
• 10-30-2009
grib
Code:

`std::cout << (Number*(Number+1)/2) << std::endl;`
:)

or, if you want to learn programming, consider two loops. I am going to write the outer loop for you, because this is a good habit to get into early while you are learning
Code:

```while(std::cin >> Number && Number > 0) {     int Sum = 0;     for(....)     std::cout << Sum; }```
This solves a lot of common bugs, first off realize that && is left to right, so the left hand side gets evaluated first, the right hand side is evaluated only when the left is true. The result of a stream input operation, is a stream. This is what lets you do cin >> a >> b; If you evaluate a stream in a boolian context it is true only if all the operations prior to this have been successful. If someone inputs 15, and then a letter your program loops forever, when done this way it exits.
• 10-31-2009
iMalc
Not trying to suggest that you don't sum up those numbers, but the formula:
y = x*(x+1)/2 gives the sum you are calculating.
You can at least use that to check that your answers are correct.