If you just need to sum number from
x
to
(y-1)
, then why don't you simplify the approach?
The following code would do the trick:
#include <iostream>
using namespace std;
int main()
{
int x, y, sum = 0;
cout << "enter x y " << endl;
cin >> x >> y;
if (y < x)
swap(x,y);
for (int i=x; i<y; ++i)
sum += i;
cout << "sum = " << sum << endl;
}
Also, knowing that
1 + 2 + 3 + ... + n = n * (n + 1) / 2
you could write
#include <iostream>
using namespace std;
int main()
{
int x, y;
cout << "enter x y " << endl;
if ( x > y ) swap(x,y);
int sum = y*(y+1)/2 - x*(x+1)/2;
cout << sum;
}