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?
#include <iostream>
usingnamespace 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;
}
#include <iostream>
#include <string>
usingnamespace 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;
}