Control Flow: Loops (for, while, do-while)

Implementing repetitive tasks using `for`, `while`, and `do-while` loops.


The do-while Loop in C

The do-while loop in C is a control flow statement that allows you to execute a block of code repeatedly, similar to the while loop. However, the key difference lies in when the condition is checked. In a do-while loop, the code block is executed at least once, regardless of whether the condition is initially true or false. The condition is evaluated after each iteration of the loop.

Syntax of the do-while Loop

The syntax for the do-while loop in C is as follows:

do {
    // Code to be executed repeatedly
} while (condition); 
  • do: This keyword signifies the start of the do-while loop.
  • { ... }: The code block enclosed in curly braces contains the statements that will be executed repeatedly.
  • while (condition): This keyword, followed by a condition enclosed in parentheses, determines whether the loop will continue to execute. The condition is evaluated after each iteration. If the condition evaluates to true (non-zero), the loop continues. If it evaluates to false (0), the loop terminates.
  • ;: Notice the semicolon at the end of the while statement. This is a crucial part of the do-while loop syntax and must be included.

Key Difference: Execution at Least Once

The fundamental difference between the while loop and the do-while loop is the order in which the condition is checked. In a while loop, the condition is checked before the loop body is executed. If the condition is initially false, the loop body is never executed.

In contrast, the do-while loop executes the loop body first and then checks the condition. This guarantees that the loop body will be executed at least once, even if the condition is initially false.

Example

#include <stdio.h>

int main() {
    int i = 0;

    do {
        printf("This will print at least once. i = %d\n", i);
        i++;
    } while (i < 5);

    return 0;
} 

In this example, the loop will execute five times, even though i is initialized to 0. The printf statement will be executed each time, and i will be incremented until it reaches 5, at which point the condition i < 5 becomes false, and the loop terminates.

Use Cases for do-while Loops

The do-while loop is particularly useful in situations where you need to execute a block of code at least once, regardless of the initial condition. Some common use cases include:

  • Menu-driven programs: When presenting a menu to a user, you typically want to display the menu options at least once before checking if the user wants to exit.
  • Input validation: When prompting the user for input, you might want to repeatedly prompt them until they enter a valid value. The do-while loop ensures that the prompt is displayed at least once.
  • Game loops: In game development, you often need to execute the game logic (e.g., updating game state, rendering graphics) at least once per frame.
  • Reading data until a sentinel value: If you are reading data from a file or other source until a specific "sentinel" value is encountered, you may need to read at least one piece of data before checking for the sentinel.

Example: Input Validation

#include <stdio.h>

int main() {
    int age;

    do {
        printf("Enter your age (must be between 0 and 120): ");
        scanf("%d", &age);

        if (age < 0 || age > 120) {
            printf("Invalid age. Please enter a value between 0 and 120.\n");
        }
    } while (age < 0 || age > 120);

    printf("Your age is: %d\n", age);

    return 0;
} 

In this example, the program repeatedly prompts the user for their age until they enter a valid value between 0 and 120. The do-while loop guarantees that the prompt is displayed at least once, even if the user initially enters an invalid age.