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