Do-While Loop in C

The do-while loop in C is used to execute a block of code at least once, and then repeatedly while a specified condition is true. Unlike the while loop, the condition is checked after the loop body executes.

Syntax

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

Example

int i = 1; do { printf("%d\n", i); i++; } while (i <= 5); // Output: 1 2 3 4 5

How It Works

  • The loop body executes first, before the condition is checked.
  • After executing the body, the condition is evaluated.
  • If the condition is true, the loop repeats; if false, it stops.
  • Ensures that the loop executes at least once regardless of the condition.

Tips

  • Use do-while when the loop must run at least once, e.g., menu-driven programs.
  • Ensure the condition eventually becomes false to prevent infinite loops.
  • Keep the loop body simple for clarity.
  • Use proper indentation and braces `{}` to avoid confusion.

Common Mistakes

  • Forgetting the semicolon after the while(condition) statement.
  • Writing conditions that never become false, causing infinite loops.
  • Confusing do-while with while loops (do-while executes at least once).
  • Complex loop bodies that make logic hard to follow.