Indefinite loops where the first time is different

Posted by George T on Programmers See other posts from Programmers or by George T
Published on 2014-06-09T14:29:24Z Indexed on 2014/06/09 15:40 UTC
Read the original article Hit count: 287

Filed under:
|

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 gotos:

    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.

© Programmers or respective owner

Related posts about algorithms

Related posts about loops