Just Keep Asking

As you frist explore programming, you may find yourself presented with a common puzzle: How to fetch proper input from a stubborn user. The solution is something I call the Just Keep Asking loop.

For example, you have a game and the user needs to input a positive value for the number of enemies. And they type none (a string) or 0 (zero, out of range). How do you handle that in a manner other than just quitting the program?

The solution is to keep asking.

The improper way to keep asking — and an approach attempted by many beginners — is to fashion a complex series of ifelse statements that continually probe for input. That method may work, but it’s inelegant.

Common programmer parlance for something inelegant is kluge (klooj). The term is from the German word for “clever,” but it’s changed over the years to mean something clumsy. It’s also spelled kludge.

Programs repeat code through the courtesy of a loop. The key to a Just Keep Asking loop is to break out of the loop once the user provides the correct input. So the loop is a waiting loop, which is quite common in the world of programming, especially when it comes to input.

In the following code, the user is prompted to type a value between 1 and 20 (inclusive). The prompt is contained within the loop — another solution many beginners don’t think of, but it’s a good idea. Otherwise, the prompt may slide up the screen and out of view.

#include <stdio.h>

int main()
{
    int a = 0;

    while(a < 1 || a > 20)
    {
        printf("Input a value between 1 and 20: ");
        scanf("%d",&a);
    }
    puts("Thank you");

    return(0);
}

To make the while loop at Line 7 work, the value of variable a must be initialized. That's done at Line 5 where the variable is declared. Otherwise, the garbage value in an uninitialized variable a might actually cause the loop to pass and the prompt never to appear.

Always initialize the variable when using a Just Keep Asking loop.

With variable a set to zero, the prompt at Line 9 is displayed and input fetched at Line 10. The loop repeats as long as input is outside the range set at Line 7. It repeats over and over when the user is stubborn, but the hope is that eventually the proper value is input and the program continues.

This type of defensive coding (also known as bullet proofing) can be modified further. For example, you could specify that typing 0 ends the program. Or you could add a counter so that the program terminates if the user doesn't input a proper value after three tries. I urge you to attempt these modifications on your own.