while and do-while loops
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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).
- Line 1: or the loop never ends
Example 1 · Sum of the digits
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(); }}Enter a number: 4072 Sum of digits: 13
What this code does
- Each round takes the last digit with
n % 10and adds it: 2, then 7, then 0, then 4. n / 10then drops that digit, songoes 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
Variables
- n
- 472
Output
(nothing printed yet)Line 3The start goes before the loop: n holds the number.
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
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(); }}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.
- Line 1: the ; is needed
Example 3 · Ask for the PIN until it is right
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(); }}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.
pinis declared before thedo, 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