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?

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
39
40
41
42
43
44
45
46
47
48
49
 
#include <iostream>

 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<<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;
    
    
        return 0;
        
        
    }
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.

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
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>

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.
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
#include <iostream>
#include <string>
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.