Lesson 71 +10 XP

Do/While Loop

Do/While Loop

A do/while loop is the mirror of a while loop: it runs the body first and checks the condition later.

The shape

do {
  // body, runs before the check
} while (condition);
  • Run the body.
  • Then check the condition.
  • If it is true, run the body again.
  • Repeat until the condition is false.

It always runs at least once

The condition is checked at the bottom, so the body is guaranteed to run at least one time even if the condition is false from the very start.

#include <iostream>
using namespace std;

int main() {
  int i = 0;
  do {
    cout << i << endl;
    i++;
  } while (i < 5);
  return 0;
}

This prints the numbers 0 to 4, exactly like the while version, because the check drives the same stopping point.

Why it is great for menus

LearnCpp 8.9 points at the classic example: a menu. You must show the menu at least once, then keep showing it until the user picks the exit option.

int choice;
do {
  cout << "1. New game  2. Quit" << endl;
  cin >> choice;
} while (choice != 2);

A plain while would test the choice before any input exists, which does not fit a first visit.

TL;DR

  • do { ... } while (condition); runs the block first, checks after.
  • The body always runs at least one time.
  • Use it when something must happen once and then be repeated.
  • Menus that must appear before any choice are a classic use.