Course contentsShow
← C
Lesson 277 of 1,2194. Control FlowFree lesson

Using do-while for input re-prompting

Using do-while for input re-prompting

What you'll learn: How to use the do-while loop to force a user to provide valid data before the program continues.

The "Ask First, Check Later" Approach

Imagine you are a bouncer at a club. You don't just stand there staring at people; you wait for someone to approach, ask for their ID, and then decide if they can enter. If their ID is invalid, you ask again.

In C programming, the standard while loop checks a condition before running the code inside. However, when you need to get input from a user, you usually want to run the code at least once. After all, you can't check if a user's number is "correct" until they have actually typed something! This is where the do-while loop shines. It guarantees that the code block executes at least once, then repeats as long as the input remains invalid.

Guaranteing Valid Input

A common use case is ensuring a user enters a positive number. If they enter a negative number, the program should stubbornly ask again and again until they cooperate.

#include <stdio.h>

int main() {
    int age;

    do {
        printf("Please enter your age (must be 0 or greater): ");
        scanf("%d", &age);
        
        if (age < 0) {
            printf("Invalid input! Age cannot be negative.\n");
        }
    } while (age < 0);

    printf("Thank you! You entered: %d\n", age);
    return 0;
}

How It Works

  1. The Do Phase: The program enters the loop immediately. It prints the prompt and waits for the user to type a number into the age variable.
  2. The Logic Check: Once the user hits enter, the program reaches the while (age < 0); line at the bottom.
  3. The Loop Decision: If the age is negative, the condition is true, so the program jumps back to the top of the do block to ask again. If the age is 0 or higher, the condition is false, the loop breaks, and the program moves on to the final "Thank you" message.

Notice the semicolon ; at the very end of the while statement. Unlike a standard while loop, the do-while requires this semicolon to signal the end of the loop structure.

Key takeaway

Use a do-while loop for input validation because it ensures your code runs at least once to collect data before testing if that data is valid.