Can you provide an example of when a do-while loop would be useful?

QuestionsQuestions4 SkillsProRecursion and LoopsAug, 27 2025
0176

Certainly! A common scenario where a do-while loop is useful is in user input validation, where you want to ensure that the user is prompted at least once before checking their input.

Example: User Password Input

Imagine you want to prompt the user to enter a password. You want to ensure that the user is prompted at least once and that the input is validated to meet certain criteria (e.g., minimum length). If the input is invalid, the user should be prompted again.

Here's how you could implement this using a do-while loop:

#include <stdio.h>
#include <string.h>

int main() {
    char password[100];
    int valid = 0;

    do {
        printf("Enter your password (at least 6 characters): ");
        scanf("%s", password);

        // Check if the password meets the criteria
        if (strlen(password) >= 6) {
            valid = 1; // Set valid to true
            printf("Password accepted.\n");
        } else {
            printf("Password too short. Please try again.\n");
        }
    } while (!valid); // Continue until a valid password is entered

    return 0;
}

Explanation:

  • The user is prompted to enter a password.
  • The loop checks if the password length is at least 6 characters.
  • If the password is valid, the loop exits; if not, the user is prompted again.
  • The do-while loop ensures that the user is asked for a password at least once, regardless of the initial input.

This pattern is particularly useful for scenarios where you want to guarantee at least one execution of the loop body before checking the condition.

0 Comments

no data
Be the first to share your comment!