Mojo - 9 months ago 50

C++ Question

wasn't quite sure how to title this question

example: cin >> 5, cout << 1+2+3+4+5

i'm in a c++ class in college and we are just starting out. I know i need to use a for or while loop but i have no idea what goes where in order for it to print what i'm looking for which is the sum of every number 1 to x (x being the user inputed number)

`#include <iostream>`

using namespace std;

int main()

{

int x, i ;

int sum = 0 ;

cout << "Please enter a single digit integer: " ;

cin >> x ;

for(i = 1 ; i <= x ; i++)

if(x <= 9)

sum = x + i ;

cout << sum << endl ;

}

i know this is probably way off, but i wanted to give you guys what i have so far. please help!

Answer

- remove the
`if`

. It does not affect your code. (Just ruins it if`x > 9`

) `sum = sum + i;`

otherwise, you just delete its value. More elegant would be`sum += i;`

That should look like that:

```
int main()
{
int x, i;
int sum = 0;
cout << "Please enter a single digit integer: " ;
cin >> x ;
for(i = 1 ; i <= x ; i++)
sum += i;
cout << sum << endl ;
}
```

As others noted, you can use the mathematical solution that states
`sum(i) from i=1 to n = n * (n+1) / 2`

, then:

```
int main()
{
int x, i;
int sum = 0;
cout << "Please enter a single digit integer: " ;
cin >> x ;
cout << x * (x + 1) / 2 << endl ;
}
```

Source (Stackoverflow)