Getting rid of that "+" sign..

hey guys, first time posting but i'm writing a pretty simple program used to "Compute and print the sum of the integers between the two numbers inclusive"
here's my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
#include<cmath>
using namespace std;

int main()
{
    int x, sum = 0, y;
    cout << "Input two integers: ";
    cin >> x >> y;
    cout << " " << endl;
    cout << "Sum of values from " << x;
    cout << " through " << y << " is:" << endl;
    cout << " " << endl;
    if(x < y)
    {
         while (x <= y)
         {
          sum += x;
          cout << x << " + ";
          x++;
         }
          
          
    }
    else 
    {
         while (y <= x)
         {
          sum += y;
          cout << y << " + ";
          y++;
         }
    }    
cout << "= " << sum << endl;
cout << " " << endl;
system ("pause");
return 0;
}


it works exactly the way it's suppose to, but i can't figure out how to get rid of the extra + sign right before the = sign when run in cmd. Any help would be great.

You could check in the while loop whether you need to print the + sign and only do so then.
Zhuge: i thought about that but im not quite sure how i would implement that, i figured i was just making rookie mistakes and my eyes didn't catch something in my code.
Did you try just using a if statement inside the loop?
How about changing the while loops from <= to just < then have the last sum operation performed just after the loop with the desired print output?
iHutch105: i tried that, but i have a specific output i'm supposed to get, and if you get rid of the <= it makes it one less than it should be. Ex. (3, 5) = 3 +4 + 5 = 12, vs (3, 5) = 3 + 4= 7.
I ended up just adding a "0" outside of the loop right next to the "=" sign, so the output has all the numbers plus a 0..
But if you added the last sum operation just outside of the loop, you'd have the same amount of calculations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// current
while (y<=x)
{
   sum += y;
   cout << y << " + ";
   y++;
}

// suggested
while (y < x)
{
   sum += y;
   cout << y << " + ";
   y++;
}

sum += y;
cout << y << " = " << sum << endl;


No need for the pesky 0.
Last edited on
Topic archived. No new replies allowed.