Sorry, hang on, I'll put that back where it should be.
Well, I guess you can either use do...while, without the directions, or just while and put the directions and a new prompt if the int is invalid.
OK, this should do it:
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
|
/*
* This program will ask the user for two numbers between 0 and 100.
* The second number must be larger than the first.
* Then, the program will compute the sum of all the numbers between and
* including the numbers the user chose. If the user includes an invalid number,
* the program will ask the user to reread the instructions.
*/
#include <iostream>
using namespace std;
int num1, num2, total, counter;
int main() {
cout << "Please enter an integer between 0 and 100: ";
cin >> num1;
while (num1 < 0 || num1 > 100) {
cerr << "Error: Invalid integer. Please follow the directions!\n" << endl;
cout << "Please enter an integer between 0 and 100: ";
cin >> num1;
}
cout << "Please enter an integer between " << num1 << " and 100: ";
cin >> num2;
while (num2 < num1 || num2 > 100) {
cerr << "Error: Invalid integer. Please follow the directions!" << endl;
cout << "Please enter an integer between " << num1 << " and 100: ";
cin >> num2;
}
for (counter = num1; counter <= num2; counter++)
total += counter;
cout << "The total of the integers between " << num1 << " and " << num2
<< " is " << total << endl;
return 0;
}
|
By the way, it is good practice to keep the code width less than 80 characters, my IDE does it automatically, but you can wrap lines like you see with the last
cout
, as long as the semicolon (;) is at the end of the statement, not the end of the line, the compiler will ignore the fact that it's on separate lines.
Oh yeah, don't forget to include
return 0;
at the end of the program. That's another good practice thing, in this case, but often times you will need it, or your program won't function correctly. Not to mention you are declaring a function (main) of type int without having it return an integral value.