patterncppMajor
while(user == gullible)
Viewed 0 times
userwhilegullible
Problem
The goal for this project was to:
Write a program that continues to asks the user to enter any number other than 5 until the user enters the number 5.
Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program.
★ Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit.
Requires:
(I'm not doing the 2 stars one yet)
My questions are:
Write a program that continues to asks the user to enter any number other than 5 until the user enters the number 5.
Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program.
★ Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit.
Requires:
- variables, data types, and numerical operators
- basic input/output
- logic (
ifstatements,switchstatements)
- loops (
for,while,do-while)
(I'm not doing the 2 stars one yet)
My questions are:
- How can I optimize my code in every possible way? (efficiency, readability, etc)
- How can I improve the code syntax?
#include
using std::cout;
using std::cin;
int main()
{
int UserNumber = 0;
int k = 1;
while (k > UserNumber;
if (UserNumber == 5)
{
cout << "\n\n\nHey! You weren't supposed to enter 5!\n\n\n";
exit(0);
}
else if (k == 10)
{
cout << "Wow, you're more patient then I am, you win.\n\n\n";
exit(0);
}
k++;
}
}Solution
A simple rule I (and other) try to apply is : define things in the smallest possible scope.
For instance,
Similarly,
Then, computer people love counting from
Then, you'll realise that there is no need for this check, you can just move this out of the loop.
For instance,
int UserNumber = 0; can be moved inside the loop.Similarly,
k can be moved once you've made your loop a for loop : for(int k = 1; k < 11; k++).Then, computer people love counting from
0. If you write : for(int k = 0; k < 10; k++), I am used to this and I know straight-away that there will be 10 iterations. If you re-index your loop, you'll need to convert else if (k == 10) into a else if (k == 9).Then, you'll realise that there is no need for this check, you can just move this out of the loop.
Context
StackExchange Code Review Q#67829, answer score: 23
Revisions (0)
No revisions yet.