### Wrong sum result

The program is supposed to add all the integers between x and Y. Both inputs are given by the user. I keep getting the sum wrong.Can anyone see where the problem is?

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849`` `````` #include using namespace std; int main() { int x = 0,y,i; int counter = x; int sum = 0; cout<<"Input two integers:"; cin>> x; cin>> y; cout<
You have to initialize 'counter' to 'x' after you have taken the user input. If you set 'counter' to 'x' before the input it will initialize as 0.

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950`` ``````#include using namespace std; int main() { int x = 0, y, i; int counter; int sum = 0; cout << "Input two integers:"; cin >> x; cin >> y; counter = x; cout << endl; cout << "Sum of values from " << x << " through " << y << " is:\n "; if (x <= y) { for (i = x; i <= y; i++) { cout << i << "\t"; } } else { for (i = y; i <= x; i++) { cout << i << "\t"; } } while (counter <= y) { sum = sum + counter; counter++; } cout << endl; cout << "= " << sum << endl; cout << endl; system("pause"); return 0; } ``````
Last edited on
It could be simplified with a function "s".
Here is a better way to do it.
 ``12345678910111213141516171819202122232425262728293031323334`` ``````#include #include using namespace std; int s(int x, int y) { int t = 0; for(int i = x; i < y + 1; i++) { t += i; } return t; } int main() { int x, y, sum; cout << "x = "; cin >> x; cout << "y = "; cin >> y; if(x < y + 1) { sum = s(x, y); cout << "The sum between " << x << " and " << y << " is " << sum << " ." << endl; } else cout << "x must be smaller or equal to y" << endl; return 0; }``````
Topic archived. No new replies allowed.