Labs ICT
โญ Pro Login

Do-While Loop

The do-while loop is the cousin of while with one twist: it checks the condition after the body runs. That means the body always executes at least once.

The do-while Loop

Write do, then the body, then while (condition). The semicolon at the end is required โ€” don't forget it.


#include 
int main() {
  int i = 1;
  do {
    printf("Count: %d\n", i);
    i++;
  } while (i <= 5);
  return 0;
}
    
Try it Yourself โ†’

Guaranteed Execution

Even if the condition is false from the start, the body still runs once. This is handy when you need something to happen before you check โ€” like showing a menu or reading input.


#include 
int main() {
  int i = 10;
  do {
    printf("This runs once even though %d > 5\n", i);
    i++;
  } while (i <= 5);
  return 0;
}
    
Try it Yourself โ†’

while vs do-while

Use while when you might not need to run the body at all. Use do-while when the body must run at least once regardless of the condition.

๐Ÿงช Quick Quiz

Which loop runs at least once before checking the condition?