Skip to lesson

while and do-while loops

A while loop repeats as long as a condition is true, which suits jobs where nobody knows the number of rounds in advance. A do-while loop works the same way but always runs its body at least once.

The while loop

To add the digits of 4072, you take off the last digit and repeat until nothing is left, so the number of rounds depends on the number. A while loop has only a condition, such as while (n > 0).

Syntax
start
while (condition) {
body
update
}
  1. Line 1: or the loop never ends

Example 1 · Sum of the digits

DigitSum.javaJava
import java.util.Scanner;
public class DigitSum {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        System.out.print("Enter a number: ");        int n = sc.nextInt();        int sum = 0;        while (n > 0) {            sum += n % 10;            n = n / 10;        }        System.out.println("Sum of digits: " + sum);        sc.close();    }}
Sample output
Enter a number: 4072
Sum of digits: 13

What this code does

  • Each round takes the last digit with n % 10 and adds it: 2, then 7, then 0, then 4.
  • n / 10 then drops that digit, so n goes 4072, 407, 40, 4, 0 and the loop stops.

The start goes before the loop and the update inside the body, as n = n / 10 does here. The stepper counts the digits of a number the same way.

Trace the code

Count the digits of 472

public class CountDigits {
public static void main(String[] args) {
int n = 472;
int digits = 0;
while (n > 0) {
n = n / 10;
digits++;
}
System.out.println("Digits: " + digits);
}
}

Variables

n
472

Output

(nothing printed yet)

Line 3The start goes before the loop: n holds the number.

Step 1 of 13
For whole numbers, n / 10 drops the last digit (472 / 10 is 47) and n % 10 gives the last digit (472 % 10 is 2). See Arithmetic operators (opens in a new tab).

Repeat until the user says stop

A shop's billing program adds prices until the cashier types 0, and nobody knows how many items are in the basket. A stop value like this 0 is called a sentinel: the loop runs until it is read.

Example 2 · Bill total until 0

BillTotal.javaJava
import java.util.Scanner;
public class BillTotal {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int total = 0;        System.out.print("Price (0 to finish): ");        int price = sc.nextInt();        while (price != 0) {            total += price;            System.out.print("Price (0 to finish): ");            price = sc.nextInt();        }        System.out.println("Total: " + total);        sc.close();    }}
Sample output
Price (0 to finish): 120
Price (0 to finish): 45
Price (0 to finish): 80
Price (0 to finish): 0
Total: 245

What this code does

  • The first price is read before the loop, so the condition has a value to check.
  • Reading the next price is the update: it is the last line of the body.
  • The 0 is never added: the check stops the loop first.

The do-while loop

A PIN screen must ask at least once before it can check anything. A do-while loop runs the body first and checks the condition after it, so the body always runs at least once.

Syntax
do {
body
} while (condition);
  1. Line 1: the ; is needed
Picture 1 / 2
while: x is 10, so the check x < 5 is false at once. The body is skipped and runs 0 times.
Picture 1 / 2

Example 3 · Ask for the PIN until it is right

PinCheck.javaJava
import java.util.Scanner;
public class PinCheck {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int pin;        do {            System.out.print("Enter PIN: ");            pin = sc.nextInt();            if (pin != 4321) {                System.out.println("Wrong PIN");            }        } while (pin != 4321);        System.out.println("Welcome");        sc.close();    }}
Sample output
Enter PIN: 1111
Wrong PIN
Enter PIN: 4321
Welcome

What this code does

  • The question is written once: the body runs before the first check.
  • pin is declared before the do, because the condition after the body must be able to see it.

With a plain while, the question would be written twice: once before the loop and once inside it.

Choosing the loop

Any loop can be rewritten as another, but the one that fits the job makes the program shorter and easier to read. Ask one question: what decides how many rounds run?

  • A number known before the loop starts (10 rows, n subjects) → for.
  • Something that happens while looping, and maybe zero rounds (read until 0, digits of a number) → while.
  • The same, but the body must run at least once (a menu, a PIN, "play again?") → do-while.

Classify

Which loop fits?

Tap a task, then tap the loop that fits it best.

Next step

Check your understanding

9 quick questions