When I enter two numbers with the first one being smaller than the second the program functions correctly. When I enter two number with the first one being larger than the second the program command window is non-responsive after the second number is entered. Can someone please help me find what I am doing wrong?
#include <iostream>
using std::cin; using std::cout; using std::endl;
/*
* A program that finds the sum between two
* numbers provided from the user.
*/
int main()
{
cout << "Enter two number: " << endl;
int v1 = 0, v2 = 0, v3 = 0, v4 = 0, sum1 = 0, sum2 = 0;
bool lock = false; //lock to prevent both while loops executing
cin >> v1 >> v2; //reads in the two numbers from the user
v3 = v1 + 1; //variable for case 1
v4 = v2 + 1; //variable for case 2
sum1 = v1; //sum variable for case 1
sum2 = v2; //sum variable for case 2
// Case 1: The first number entered is smaller than the second
while(v3<=v2)
{
sum1 += v3;
v3++;
lock = true;
}
// Case 2: The second number entered is smaller than the first
while(lock == false)
{
while(v4<=v1)
{
sum2 += v4;
v4++;
}
}
// Print Case 1
if(lock == true)
{
cout << "The sum of " << v1 << " to " << v2 << " inclusive is " << sum1 << endl;
}
//Print Case 2
if(lock == false)
{
cout << "The sum of " << v1 << " to " << v2 << " inclusive is " << sum2 << endl;
}
system("PAUSE");
return 0;
Since I am testing for the lock to decide which print statement to print depending on the case. I have decided to use break instead of updating my lock variable.
The goal of this assignment is to use while loops. However, I am sure there probably is some fancy efficient way to do what I just did with less coding.
#include <iostream>
using std::cin; using std::cout; using std::endl;
/*
* A program that finds the sum between two
* numbers provided from the user.
*/
int main()
{
cout << "Enter two number: " << endl;
int v1 = 0, v2 = 0, v3 = 0, v4 = 0, sum1 = 0, sum2 = 0;
bool lock = false; //lock to prevent both while loops executing
cin >> v1 >> v2; //reads in the two numbers from the user
v3 = v1++; //variable for case 1
v4 = v2++; //variable for case 2
sum1 = v1; //sum variable for case 1
sum2 = v2; //sum variable for case 2
// Case 1: The first number entered is smaller than the second
if(v1<=v2)
{
while(v3<=v2)
{
sum1 += v3;
v3++;
lock = true;
}
cout << "The sum of " << v1 << " to " << v2 << " inclusive is " << sum1 << endl;
}
// Case 2: The second number entered is smaller than the first
if(lock == false)
{
while(v4<=v1)
{
sum2 += v4;
v4++;
}
cout << "The sum of " << v1 << " to " << v2 << " inclusive is " << sum2 << endl;
}
system("PAUSE");
return 0;