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:
#include<iostream>
#include<cmath>
usingnamespace 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.
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.
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;