This isn't a serious problem or anything someone has asked me to do, just a seemingly simple thing that I came up with as a mental exercise but has stumped me and which I feel that I should know the answer to already. There may be a duplicate but I didn't manage to find one.
Suppose that someone asked you to write a piece of code that asks the user to enter a number and, every time the number they entered is not zero, says "Error" and asks again. When they enter zero it stops.
In other words, the code keeps asking for a number and repeats until zero is entered. In each iteration except the first one it also prints "Error".
The simplest way I can think of to do that would be something like the folloing pseudocode:
int number = 0;
do
{
if(number != 0)
{
print("Error");
}
print("Enter number");
number = getInput();
}while(number != 0);
While that does what it's supposed to, I personally don't like that there's repeating code (you test number != 0 twice) -something that should generally be avoided. One way to avoid this would be something like this:
int number = 0;
while(true)
{
print("Enter number");
number = getInput();
if(number == 0)
{
break;
}
else
{
print("Error");
}
}
But what I don't like in this one is "while(true)", another thing to avoid.
The only other way I can think of includes one more thing to avoid: labels and goto
s:
int number = 0;
goto question;
error:
print("Error");
question:
print("Enter number");
number = getInput();
if(number != 0)
{
goto error;
}
Another solution would be to have an extra variable to test whether you should say "Error" or not but this is wasted memory.
Is there a way to do this without doing something that's generally thought of as a bad practice (repeating code, a theoretically endless loop or the use of goto
)?
I understand that something like this would never be complex enough that the first way would be a problem (you'd generally call a function to validate input) but I'm curious to know if there's a way I haven't thought of.
while(true)
I've read are a)it makes it harder for a (human) reader to know what ends the loop and b)it makes it easier for future changes to remove the clause by mistake.