reformat a while or if/else condition for a range

the user is supposed to enter a bottom number within range and a top number within range. The program works great if entering within range or outside of range. The questions or problem I have is if the user enters a number smaller on the top than the bottom:
ex:
bottom 4
top 2

it jumps to the end where my last output is. Does anyone know how to fix that top number condition?

#include<iostream>
using std::cout;
using std::cin;

int main()
{

int bottom, top;
int guess, wrong=0,correct=0, total=0;
float percentage=0;

cout<< "Enter the bottom end of the range (from -100 to 100): ";
cin >> bottom;
if(bottom < -100 || bottom > 100)
{
while(bottom < -100 || bottom > 100)
{
cout << "Out of range \n";
cout<< "Enter the bottom end of the range (from -100 to 100): ";
cin >> bottom;
}
}

cout<< "\nEnter the top end of the range (from -100 to 100): ";
cin >> top;
if(top < -100 || top > 100)
{
while(top < -100 || top > 100)
{
cout << "Out of range \n";
cout<< "\nEnter the top end of the range (from -100 to 100): ";
cin >> top;
}
}

for (int a=bottom; a<=top; a++)
{
for (int b=bottom; b<=top; b++)
{
cout << "\n\nWhat is ? " << a << " * " << b << " = ";
cin >> guess;

if (guess==a*b)
{
cout << " \n\ncorrect \n\n";
++correct;
}
else
cout << " \n\nSorry, the correct answer for "<<a<<" * "<<b<< " is "<<a*b<<"\n\n";
++ total;
}
}

percentage = static_cast<float>(correct) / total;
wrong=total-correct;

cout << "You answered " << total << " questions in total.\n\n";
cout << wrong <<" were answered wrong.\n\n";
cout << "This gives you a " << percentage * 100 << "% rate.\n";


return 0;
}
Last edited on
You could wrap your input loops with a
1
2
3
do{
 ...
}while( top >= bottom );


By the way, your input loops are a bit redundant.
You could have instead
1
2
3
4
5
6
while( true ) {
   cout << "Enter the bottom end of the range (from -100 to 100): ";
   cin >> bottom;
   if( bottom < -100 || bottom > 100  ) cout << "Out of range";
   else break;
}
Not that it really makes any difference...
Topic archived. No new replies allowed.