C do-While Loop

The do-while loop in C is a control flow statement that executes a block of code at least once and then repeatedly executes the block as long as a specified condition remains true. Unlike the while loop, which checks the condition before executing the loop body, the do-while loop checks the condition after executing the loop body.

Syntax of the do-while Loop

do {
// Code to be executed
} while (condition);

do Keyword: Marks the beginning of the loop.

Code Block: The block of code within the curly braces {} is executed at least once and then repeatedly based on the condition.

while Keyword: Follows the code block and is followed by a condition in parentheses (). After the code block executes, the condition is evaluated. If true, the loop repeats; otherwise, it terminates.

How the do-while Loop Works

1. Execute Code Block: The code inside the do block executes once unconditionally.

2. Condition Check: After the code block execution, the condition is evaluated.

     • True: If the condition is true, the loop repeats, executing the code block again.

     • False: If the condition is false, the loop terminates, and execution continues with the code after the do-while loop.

Example 1: Password Verification

This example demonstrates how to use a do-while loop to prompt the user for a password until the correct one is entered:

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

int main() {
    char correctPassword[] = "password123";
    char userInput[50];

    do {
        printf("Enter your password: ");
        scanf("%s", userInput); // Read user input
    } while (strcmp(userInput, correctPassword) != 0); // Compare input with correct password

    printf("Access granted!\\n");
    return 0;
}

Example 2: Sum of User-Entered Numbers

This example uses a do-while loop to repeatedly ask the user to enter numbers and computes sum of positive numbers. The loop continues until the user enters a negative number:

#include <stdio.h>

int main() {
    int number, sum = 0;

    do {
        printf("Enter a number (negative to stop): ");
        scanf("%d", &number); // Read user input
        if (number >= 0) {
            sum += number; // Add positive numbers to sum
        }
    } while (number >= 0); // Continue looping as long as the number is non-negative

    printf("Total sum: %d\\n", sum);
    return 0;
}

Output:

Enter a number (negative to stop): 10
Enter a number (negative to stop): 20
Enter a number (negative to stop): 30
Enter a number (negative to stop): 40
Enter a number (negative to stop): -1
Total sum: 100