A do while loop in C is a control structure that repeats a block of code at least once and then continues repeating it as long as a condition remains true.

Basic idea (in simple words)

  • The body of the loop runs first.
  • After that, the condition is checked.
  • If the condition is true, the loop repeats; if false, it stops.
  • Because the condition is checked at the end, the body runs at least one time, even if the condition is false initially.

Syntax of do while loop in C

c

do {
    // code to be executed
} while (condition);
  • Notice the semicolon ; after the while(condition) β€” this is required for a do while loop.

Simple example

c

#include <stdio.h>

int main() {
    int i = 0;

    do {
        printf("%d\n", i);
        i++;
    } while (i < 5);

    return 0;
}
  • This prints the numbers 0 to 4, one per line.
  • Even if you start with int i = 10;, the body would still run once before checking i < 5.

Key properties

  • It is an exit-controlled loop: condition is tested at the end of each iteration.
  • Guarantees at least one execution of the loop body.
  • Good for menus, user-input loops, or situations where you want the action to happen once before checking whether to continue.

Mini comparison: while vs do while

[1][6][7]
Feature while loop do while loop
Condition check position Before the body After the body
Minimum executions 0 (may never execute) 1 (always executes once)
Syntax end No semicolon after while Requires semicolon after while(condition);
[3][7]

Tiny β€œstory” example (menu-style)

Imagine a console menu that must show at least once and repeat until the user chooses Exit:

c

int choice;

do {
    printf("1. Start\n");
    printf("2. Exit\n");
    printf("Enter choice: ");
    scanf("%d", &choice);
} while (choice != 2);
  • The menu shows first, then the condition choice != 2 decides if it should appear again.

TL;DR: A do while loop in C runs its block first and checks the condition afterward, ensuring the block executes at least once and then repeats while the condition is true.

Information gathered from public forums or data available on the internet and portrayed here.