c++ - Making my do while loop neater by removing repeating code -
hi here question.
write program uses do-while statement. reads in integer n keyboard. if n not in range 1 10 makes audible “beep” , asks integer. if n in correct range, writes out “you have input n” , exits.
here answer.
#include <iostream> #include <windows.h> using namespace std; void main() { int number = 0; { cout << "enter integer." << endl; cin >> number; if (!(number >= 1 && number <= 10)) { beep(400, 400); } } while (!(number >= 1 && number <= 10)); cout << "you have input " << number << endl; system("pause"); }
you can see line
(!(number >= 1 && number <= 10))
is repeated. there workaround this?
#include <iostream> #include <windows.h> using namespace std; void main() { int number = 0; bool invalid_input = true; { cout << "enter integer." << endl; cin >> number; invalid_input = !(number >= 1 && number <= 10); if (invalid_input) { beep(400, 400); } } while (invalid_input); cout << "you have input " << number << endl; system("pause"); }
Comments
Post a Comment