Labs ICT
โญ Pro Login

Do-While Loop

1 min read | C Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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 <stdio.h>
int main() {
  int i = 1;
  do {
    printf("Count: %d\n", i);
    i++;
  } while (i <= 5);
  return 0;
}
    

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 <stdio.h>
int main() {
  int i = 10;
  do {
    printf("This runs once even though %d > 5\n", i);
    i++;
  } while (i <= 5);
  return 0;
}
    

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?