CodeBlanks Logo Icon CodeBlanks

do-while

Learn do-while loops that run at least once.

do-while

The do-while loop runs the body first, then tests the condition. So the body always runs at least once.

int n = 5;
do {
    System.out.println(n);
    n--;
} while (n > 0);

Here 5, 4, 3, 2, 1 is printed. Because the condition is tested after the body, the first turn always runs. The semicolon after the while line is required. It is handy for flows like menus that must be shown at least once.

do-while vs while

while tests the condition first; if it is false on the first turn, the body never runs. do-while tests at the end; the body always runs at least once.

int n = 10;
// while: never runs
while (n < 5) {
    System.out.println(n);
}
// do-while: runs once
do {
    System.out.println(n);
} while (n < 5);

Use do-while when the first turn must happen; otherwise prefer while.

Practice do-while from 3 to 1

Write a Main class with a main method. Assign 3 to int n. With do { ... } while (n > 0); print System.out.println(n) each turn and decrement with n--.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        int n = 3;
        do {
            System.out.println(n);
            n--;
        } while (n > 0);
    }
}

Expected output

3
2
1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many times does a do-while body run at minimum?

  • 1 Correct answer
  • 0
  • 2
  • Depends on the condition

Explanation: A do-while body runs at least once.

2 Complete the do-while

Question
int n = 3;
do {
    System.out.println(n);
    n--;
} ____ (n > 0);
Answer
int n = 3;
do {
    System.out.println(n);
    n--;
} while (n > 0);

Explanation: do-while ends with while and a semicolon.

3 Match the do-while concepts

Term Meaning
do Body start
while Condition
; Closing
at least 1 Run count

All lessons in Beginner