Loop output slight error

Nov 20, 2021 at 6:03am
Hello I have a slight error in my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int sum=0, lastValue, num=1;

cout <<"Enter a number for the last value: ";
cin >> lastValue;

do
{
cout <<num<<"+";
sum+=num;
num++;

}while( num<=lastValue );

cout << endl;
cout <<"Sum: "<<sum;



The output is this:
Enter a number for the last value: 20
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+
Sum: 210
And the problem is it adds the plus sign at the end of the last number.
What can I do so that the plus sign won't appear on the last number?
Nov 20, 2021 at 6:37am
Don't print out a plus sign before you know if there will be another number.

You can do while (num < lastValue) instead of (num <= lastValue), and then at the end, just cout << lastValue. And then just handle edge cases like if the user enters 0.
Last edited on Nov 20, 2021 at 6:38am
Nov 20, 2021 at 6:55am
It works but the last value won't be added to the sum,
the sum of the output is 190 instead of 210
Nov 20, 2021 at 6:59am
And I haven't heard of edge cases
Nov 20, 2021 at 7:06am
Ohh I figured it out, thanks for the help sir
Topic archived. No new replies allowed.