adding all values inside for loop

So the user inputs two integers (for examples 1 and 4) and the output looks like this: +1 +2 +3 +4 which is what I want. Except that I have no idea how to add them up? so the answer would print out +1 +2 +3 +4 = 10. I've tried sum+=i but that prints out +11 +21 +31 +41. Any ideas?

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


using namespace std;

int main()
{
	int int1;
	int int2;
	int i;
	int sum;
	
	cout << "Input two integers: " << endl;
	cin >> int1 >> int2;

	if ( int1 < int2 )
	{
		for (i = int1; i <= int2; i++)
		{
			cout << " + " << i;
			
		}

		
	}
	
	else
	{
		for (i = int2; i <= int1; i++)
		{
			cout << " + " << i;
					
		}
	}

	return 0;
}
closed account (2UD8vCM9)
You'd declare an int to store the sum outside the loops and increment it like so
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
#include <iostream>


using namespace std;

int main()
{
	int int1;
	int int2;
	int i;
	int sum=0;
	
	cout << "Input two integers: " << endl;
	cin >> int1 >> int2;
 
	if ( int1 < int2 )
	{
		for (i = int1; i <= int2; i++)
		{
			cout << " + " << i;
			sum+=i;
		}

		
	}
	
	else
	{
		for (i = int2; i <= int1; i++)
		{
			cout << " + " << i;
			sum+=i;		
		}
	}
         cout << "Sum:"<< sum << endl;
	return 0;
}
s
Last edited on
hey thanks for your help!
Topic archived. No new replies allowed.