C Do While Loop

The do/while loop is a variant of the while loop. The big difference is that it always runs the code block at least once, because the condition is checked at the bottom instead of the top.

The do/while Loop

A do/while loop first runs the body once, then checks the condition. If the condition is true, it runs the body again, and it keeps going until the condition becomes false. This guarantees the code inside runs a minimum of one time.

A basic do/while loop

#include <stdio.h>

int main() {
  int i = 0;
  do {
    printf("i is %d\n", i);
    i++;
  } while (i < 5);
  return 0;
}

This prints 0 through 4, just like the while loop version. Notice that the condition (i < 5) sits at the end after the closing brace, and the line must end with a semicolon.

Note: Do not forget the semicolon after the while condition in a do/while loop. Leaving it out is a common beginner mistake that causes a compile error.

Runs at least once even when the condition is false

#include <stdio.h>

int main() {
  int i = 10;
  do {
    printf("This runs once, i is %d\n", i);
    i++;
  } while (i < 5);
  return 0;
}

Even though i starts at 10 and the condition i < 5 is already false, the body still runs one time. A regular while loop would have printed nothing here. This makes do/while perfect for menus and prompts that must show at least once.

  • The body runs first, then the condition is checked.
  • The block always executes at least one time.
  • Great for input menus that repeat until the user chooses to quit.
LoopCondition checkedMinimum runs
whileBefore the body0
do/whileAfter the body1