For loop to add int between two numbers

The for loop outputs all numbers in between adding up. how can I output just the sum? Can anyone see where I went wrong.
this is the program
Write a program that asks the users for two integers, x and y. It should then add up all the integers between (and including) x and y and output the result. Your program should work correctly if x > y or if x < y. If x and y are equal to each other, your program should ask the user for two numbers again and repeat until the user provides different values.
heres my code hope you can help

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>
using namespace std;

int main()
{
int minNum, maxNum,num, sum = 0;

// enter 2 numbers
cout << ("enter first number \n");
cin >> minNum;
cout << ("enter second number \n");
cin >> maxNum;
/*If x and y are equal to each other, your 
program should ask the user for two numbers again 
and repeat until the user provides different values.*/
while (minNum == maxNum)
{
	cout << " The numbers equal each other. enter the two numbers again \n";
}
/cin >> minNum;
cin >> maxNum;
*It should then add up all the integers between
(and including) x and y and output the result.*/
for (num = minNum; num <= maxNum; num++)
{
	sum += num;
	cout << sum << endl;
}


system("pause");
return 0;
}
 
Last edited on
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()
{
	//changed min and max with x and y 

	int x,y, num, sum = 0;

	// enter 2 numbers
	cout << ("enter first number \n");
	cin >> x;
	cout << ("enter second number \n");
	cin >> y;
	/*If x and y are equal to each other, your
	program should ask the user for two numbers again
	and repeat until the user provides different values.*/
	while (x == y)
	{
		cout << " The numbers equal each other. enter the two numbers again \n";
		cin >> x;//If user again enters equal numbers we repeat
		cin >> y;
	}
	//By this point we do not know which is higher lets check it
	int higher_num;
	int lower_num;
	if (x > y)
	{
		higher_num = x;
		lower_num = y;
	}
	else
	{

		higher_num = y;
		lower_num = x;
	}
	//you could use ternary operator
	//higher_num=x>y ? x:y;
	//lower_num=y<x ? x:y;
		for (num = lower_num; num <= higher_num; num++)
		{
			sum += num;
			
		}
		cout << sum << endl;

	system("pause");
	return 0;
}

EDIT:If you do now know where you have went wrong put a breakpoint and start watching your program.Believe me,by debugging you will become much better programmer .
Last edited on
Thanks Zivojin I wouldn't have thought of the if/else Thanks for the tip too. how would I convert this to a while loop ? thanks again !!
Topic archived. No new replies allowed.