I can't seem to make it so only one of the two statement appear.
In this program, when a user enters two numbers, if the first number entered is smaller, I want the first statement to appear. If the first number is larger I want the second statement to appear.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<iostream>
int main()
{
std::cout << "Enter two numbers: ";
std::cout << std::endl;
int v1 = 0, v2 = 0, sum = 0, val;
std::cin >> v1 >> v2;
val = v1;
while (val <= v2) {
sum += val;
++val;
}
std::cout << "The sum of " << v1 << " to " << v2 << " inclusive is: " << sum;
std::cout << std::endl;
std::cout << "The sum of " << v2 << " to " << v1 << " inclusive is: " << sum;
std::cout << std::endl;
return 0;
}
Your if code is ok. The problem is in calculating the sum. So, pick two numbers say 3 and 4 and write down the response as each line is processed in the while loop, and you'll see that the sum is 0 for one of the cases where x<y or x>y.
Line 10 means the sum is always zero for val ( i.e v1 ) >v2
So if you want both answers to be the same then you'll have to swap v1 and v2 around.
Yeah you could do the test first, swap the numbers around, calculate the sum and display the answer That way you only have one set of while/cout statements not two.
1. User inputs two integars
2. Program forces smaller integar to go first in calculation.
3. The program will calculate smaller to bigger integar to find result even if user inputs bigger integar first.
ex.
If I input 20 then 10, the program will say:
"10 to 20 is...."
If I input 10 then 20, the program will say:
"10 to 20 is..."
The last code I wrote does that(what I wanted). But can I make that more efficient? Or is that pretty solid code?
That's the idea :-) Try it out. The only thing to watch is to avoid duplicating code when it isn't necessary. This applies to the message display. You're on the right track.