while and do-while loops

A for loop is perfect when you know how many times to repeat. But how many months until Riya's savings reach ₹10,000? How many digits does a number have? How many tries until the right PIN? When the answer is “until something happens”, you use a while loop, or a do-while when the body must run at least once.

Module 3 · Control Flow⏱ 19 minBeginner10 practice problems
1 The story

How many months to the new phone?

Riya wants a ₹10,000 phone. She can save ₹1,500 a month. She starts writing a for loop, then stops: for how many months? That's the very thing she's trying to find out.

Goal ₹10,000 M1M2M3M4M5M6M7 ✓ 15003000450060007500900010500 myphatshala.in
Riya

Sir, I need a loop, but I don't know how many times it should run. That's the question!

Arjun Sir

Then don't count. Say what should keep it going: “while my savings are below ₹10,000, add another month”. Java checks the condition before each month and stops the moment it's false.

Riya

And I count the months inside the loop to get the answer.

Arjun Sir

Exactly. And there's a cousin, do-while, that runs the body first and checks afterwards. Let's see when each one is right.

2 Definition

What are while and do-while?

Formal definition (write this in exams)

The while loop (while (condition) { body }) is an entry-controlled loop: the condition is evaluated before each iteration, so the body may execute zero times. The do-while loop (do { body } while (condition);) is an exit-controlled loop: the body executes first and the condition is evaluated afterwards, so the body executes at least once.

In simple words

while: “check, then do”. Like checking the queue before joining: if nobody's there, you skip it entirely. do-while: “do, then check”. Like tasting the chai and then deciding whether it needs more sugar: you always taste at least once.

Words you'll meet in this lesson

Entry-controlledCondition checked before the body (for, while). May run 0 times.
Exit-controlledCondition checked after the body (do-while). Runs at least once.
SentinelA special value that means “stop”, like entering 0 to finish a list.
Infinite loopA loop whose condition never becomes false, like while (true).
Loop invariantSomething that stays true on every iteration; useful for reasoning about correctness.
Digit extractionn % 10 gives the last digit; n / 10 removes it.

The three loops compared

forwhiledo-while
Condition checkedBefore each iterationBefore each iterationAfter each iteration
Minimum runs001
Best forKnown number of repeatsRepeat until something happensDo once, then maybe repeat (menus, input checks)
Syntax ends with}}} while (cond); ← semicolon

Exam tip: the do-while ends with a semicolon after the condition; forgetting it is a compile error. For a while loop, the variables in the condition must be changed inside the body, or the loop never ends.

3 Types and ways to use it

Common while-loop patterns

Until a goal is reached

while (savings < goal) { … }
Savings, loan payoff, population growth.

Unknown count
4729

Digit by digit

while (n > 0) { d = n % 10; n /= 10; }
Reverse, count or add digits.

Number tricks

Sentinel input

Read numbers until the user enters 0, or lines until “exit”. The stop value isn't processed.

Input

Server loop

while (running) { handle(next()); }
Keeps a service or game running until told to stop.

Long-running

When do-while is the natural choice

SituationWhy do-while
Showing a menuThe menu must appear at least once before the user can choose “Exit”.
Asking for input until it's validYou must ask once before you can check the answer.
Processing the digits of a number, including 00 has one digit; a while loop with n > 0 would count zero digits.
4 Step by step

Writing a while loop that always ends

  1. Set up variables before the loop

    int savings = 0;
    int months = 0;
    Unlike for, while has no init part. Everything the condition uses must already exist.
  2. Write the condition as “keep going while…”

    while (savings < 10_000) {
    javac puts the check at the top: if it's false, jump past the loop (if_icmpge). That's why a while loop can run zero times.
  3. Make progress inside the body

        savings += 1_500;
        months++;
    }
    Each iteration must move the condition closer to false. Here savings grows, so eventually it reaches 10,000. If nothing changes, it's an infinite loop.
  4. Use the result after the loop

    When the loop ends, the condition is guaranteed to be false: savings >= 10_000. months holds the answer.

    At the end of the body, a goto jumps back to the check. When the check fails, execution continues after the loop.
  5. Switch to do-while when the body must run first

    do {
        digitSum += n % 10;
        n /= 10;
    } while (n > 0);
    In bytecode, a do-while has its condition at the bottom: ifgt jumps back to the start if it's true. There's no check before the first iteration.
5 See it happen

Check first, or do first? Both views

Left: the code and output. Right: the order of check and body, and the bytecode shape.

while vs do-while 6 steps
What you see while (savings < 10_000) { savings += 1_500; months++;} do { digitSum += n % 10; n /= 10;} while (n > 0); n = 0; while (n > 0) { count++; … }n = 0; do { count++; … } while (n > 0); savings = 0, months = 0 month 1: 1500 · month 2: 3000 · … month 6: 9000 (still < 10000) Goal reached in 7 months: Rs 10500 n = 4729 → 9 + 2 + 7 + 4 Digit sum: 22 while → digits counted: 0 ✗ do-while → digits counted: 1 ✓ The condition is checked before every month. Each month moves savings closer to the goal. 10500 < 10000 is false: the loop ends. do-while: the body runs first. The check comes after each pass. For 0, “at least once” is exactly right. myphatshala.in
Behind the screen savings<10000? body false after loop L: iload savings sipush 10000 if_icmpge END … body … goto LEND: … Check at the top: if already ≥ 10000, the body never runs. savings: 0 → 1500 → 3000 → … → 9000; months: 0 → 6 The 8th check fails: if_icmpge jumps to END. months = 7. body n > 0 ? true false after loop L: … body … iload n ifgt L …after loop No check before the first pass: straight into the body. n: 4729 → 472 → 47 → 4 → 0. Four passes, then ifgt fails. Bottom check = at least one pass. One less jump, too. myphatshala.in
6 Real-world use

“Until something happens” in real systems

Wherever software waits, retries, reads until the end, or runs until stopped, there's a while loop.

Watch it with an example: three tries to enter the OTP

A banking app gives you 3 attempts. A while loop keeps asking until the OTP is right or the attempts run out. Nobody knows in advance how many rounds it will take.

while (attempts < 3 && !ok) 6 steps
Animated example while (attempts < 3 && !ok) { read OTP; attempts++; } Phone OTP sent: 4821 1111 4812 4821 ✗ wrong ✓ correct attempts 0 1 2 3 3 3 ok false false false true true true condition: true → enter true → again true → again false → exit false → exit false → exit Logged in on attempt 3 myphatshala.in
EOF

1. Reading files and streams

Reading a log or CSV file line by line: while ((line = reader.readLine()) != null). Nobody knows in advance how many lines there are (Module 13).

File→while line != null→Every line processed

2. Servers and background workers

A message consumer (for example a Kafka consumer) runs while (running) { poll(); process(); } for weeks, until it's asked to shut down.

Start service→while (running) poll→Graceful shutdown
page 1 → 2 → 3next = null → stop

3. Paging through an API

Many APIs return results page by page with a “next” link or cursor. Code keeps fetching while (nextCursor != null), collecting all pages.

Fetch page→while next != null→All transactions
1. Balance4. Exit

4. Menus in terminals and kiosks

ATM-style and command-line menus use do-while: show the menu, handle the choice, repeat until the user picks Exit.

Show menu→do { … } while (choice != EXIT)→Goodbye

5. Financial projections

“How many years until this deposit doubles?” or “how many months to pay off this credit-card balance?” are while loops over months or years (see practice problem P10).

Deposit + rate→while amount < target→Years needed

Examples are simplified to show where while loops fit. Real systems add timeouts and error handling.

7 Run the code

Savings goal and digit sum

public class Main {
    public static void main(String[] args) {
        int savings = 0;
        int months = 0;
        while (savings < 10_000) {               // check first
            savings += 1_500;
            months++;
        }
        System.out.println("Goal reached in " + months + " months: Rs " + savings);

        int n = 4729, digitSum = 0;
        do {                                       // run first
            digitSum += n % 10;                    // last digit
            n /= 10;                               // remove it
        } while (n > 0);
        System.out.println("Digit sum: " + digitSum);
    }
}
Goal reached in 7 months: Rs 10500 Digit sum: 22
  • while (savings < 10_000)Keep going while the goal isn't reached. We don't need to know how many months in advance.
  • savings += 1_500;Progress: this is what eventually makes the condition false.
  • n % 10The last digit of n (4729 % 10 = 9).
  • n /= 10Removes the last digit using integer division (4729 / 10 = 472).
  • } while (n > 0);The do-while's check, at the bottom, ending with a semicolon.
8 Line by line

Watch the digits peel off

A do-while loop sums the digits of 472. Watch n shrink by one digit each pass, and where the condition is checked.

Worked examples: real problems, solved and traced in memory

Use while when you don't know in advance how many times to repeat: until a goal is reached, until a valid input arrives, until a number runs out of digits. In the traces, watch the condition being re-checked before (while) or after (do-while) each pass.

Example 1Personal finance · goals

How many months to save for a laptop?

Problem statement

A student saves Rs 3,500 a month and also earns 1% interest per month on what's saved. How many months until she has Rs 15,000 for a laptop?

Input
goal 15000, saves 3500/month, 1% per month
Expected output
Months needed: 5
Balance then: Rs 17854

Approach

  1. Start with balance 0 and months 0.
  2. While the balance is below the goal: add interest, add the saving, count a month.
  3. The loop stops as soon as the goal is reached.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 2Banking · ATM

Three PIN attempts with do-while

Problem statement

An ATM allows up to 3 PIN attempts. The customer's attempts are in an array (simulating key presses). Use a do-while: the first attempt always happens, then repeat while the PIN is wrong and attempts remain.

Input
correct PIN 4821; attempts 1234, 4812, 4821
Expected output
Attempt 1: wrong
Attempt 2: wrong
Attempt 3: correct
Card unlocked

Approach

  1. do { … } while (…) runs the body at least once.
  2. Each pass reads the next attempt and counts it.
  3. After the loop, decide: unlocked or card blocked.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 3Data · checks

Digit sum of an account number

Problem statement

Some systems use a digit sum as a quick check on account numbers. Add up the digits of 40021876 by repeatedly taking the last digit with % 10 and removing it with / 10.

Input
40021876
Expected output
8 digits, digit sum 28

Approach

  1. While the number is greater than 0:
  2. add n % 10 (last digit) to the sum, then n /= 10.
  3. Count the digits too.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

9 Quiz and revision

Check yourself

Quick revision

Lesson 3.4 in one screen

  • while (cond) { … } — entry-controlled, may run 0 times.
  • do { … } while (cond); — exit-controlled, runs at least once, ends with ;.
  • Use while when the number of iterations isn't known: goals, files, sentinels, servers.
  • The body must make progress towards ending the loop, or it's infinite.
  • Digits: n % 10 = last digit, n / 10 = remove it.
  • Bytecode: while checks at the top; do-while checks at the bottom with a backward jump.

Interview and viva questions

Difference between while and do-while?

while checks the condition before each iteration and can run zero times. do-while checks after each iteration and always runs at least once. Syntax-wise, do-while ends with a semicolon.

How do you exit an infinite while (true) loop?

With break (leave the loop), return (leave the method), an exception, or by ending the program. Long-running loops usually check a flag such as running that another part of the program can set to false.

Can a for loop always replace a while loop?

Yes: while (c) { … } is the same as for (; c; ) { … }. The choice is about readability: for says “count”, while says “until”.

What is a sentinel-controlled loop?

A loop that reads values until a special stop value (the sentinel) appears, such as 0 or “exit”. The sentinel itself isn't processed as data.

What is busy waiting, and why is it bad?

A loop that repeatedly checks a condition without pausing, like while (!ready) { }. It burns 100% of a CPU core doing nothing. Use blocking calls, sleeps with backoff, or proper concurrency tools (Module 12) instead.

Practice problems

These use while or do-while because the number of steps isn't known in advance. Try each one before opening the solution.

P1Easy

Count the digits

Count how many digits a positive number has.

Input
n = 905213
Expected output
905213 has 6 digits
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int n = 905213;
        int temp = n, count = 0;
        do {
            count++;
            temp /= 10;
        } while (temp > 0);
        System.out.println(n + " has " + count + " digits");
    }
}
905213 has 6 digits

How it works: each / 10 removes one digit, so we count how many removals it takes to reach 0. We use a copy, temp, so the original n is still available to print. do-while makes 0 correctly count as 1 digit.

P2Easy

Reverse a number

Reverse the digits of a number.

Input
n = 12345
Expected output
Reversed: 54321
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int n = 12345;
        int reversed = 0;
        while (n > 0) {
            reversed = reversed * 10 + n % 10;
            n /= 10;
        }
        System.out.println("Reversed: " + reversed);
    }
}
Reversed: 54321

How it works: take the last digit of n and “push” it onto the end of reversed by multiplying reversed by 10 and adding the digit: 0 → 5 → 54 → 543 → 5432 → 54321.

P3Easy

Product of digits

Multiply all the digits of a number together.

Input
n = 2345
Expected output
Product of digits: 120
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int n = 2345;
        int product = 1;
        while (n > 0) {
            product *= n % 10;
            n /= 10;
        }
        System.out.println("Product of digits: " + product);
    }
}
Product of digits: 120

How it works: same digit-peeling pattern, but a product accumulator starts at 1: 5 × 4 × 3 × 2 = 120.

P4Medium

Palindrome number

A palindrome reads the same forwards and backwards. Check whether a number is a palindrome.

Input
n = 12321
Expected output
12321 is a palindrome
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int n = 12321;
        int temp = n, reversed = 0;
        while (temp > 0) {
            reversed = reversed * 10 + temp % 10;
            temp /= 10;
        }
        if (reversed == n) {
            System.out.println(n + " is a palindrome");
        } else {
            System.out.println(n + " is not a palindrome");
        }
    }
}
12321 is a palindrome

How it works: reverse a copy of the number (problem P2), then compare it with the original. Keeping the original untouched is the key detail.

P5Medium

Armstrong number

A 3-digit number is an Armstrong number if the sum of the cubes of its digits equals the number itself (e.g. 153 = 1³ + 5³ + 3³). Check a number.

Input
n = 153
Expected output
153 is an Armstrong number
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int n = 153;
        int temp = n, sum = 0;
        while (temp > 0) {
            int d = temp % 10;
            sum += d * d * d;
            temp /= 10;
        }
        System.out.println(n + (sum == n ? " is" : " is not") + " an Armstrong number");
    }
}
153 is an Armstrong number

How it works: peel each digit, cube it with d * d * d (faster and exact compared with Math.pow, which returns a double), and add it up: 27 + 125 + 1 = 153.

P6Medium

GCD and LCM (Euclid's algorithm)

Find the greatest common divisor (GCD) and least common multiple (LCM) of two numbers.

Input
a = 48, b = 180
Expected output
GCD = 12, LCM = 720
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int a = 48, b = 180;
        int x = a, y = b;
        while (y != 0) {
            int remainder = x % y;
            x = y;
            y = remainder;
        }
        int gcd = x;
        int lcm = a / gcd * b;
        System.out.println("GCD = " + gcd + ", LCM = " + lcm);
    }
}
GCD = 12, LCM = 720

How it works: Euclid's rule: gcd(x, y) = gcd(y, x % y), until y is 0. Steps: (48, 180) → (180, 48) → (48, 36) → (36, 12) → (12, 0). Then LCM = a × b ÷ GCD; dividing first (a / gcd * b) keeps numbers small and avoids overflow.

P7Medium

Collatz steps

Start with n. If it's even, halve it; if odd, make it 3n + 1. Count the steps until n becomes 1.

Input
n = 27
Expected output
27 reaches 1 in 111 steps
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int start = 27;
        long n = start;
        int steps = 0;
        while (n != 1) {
            n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
            steps++;
        }
        System.out.println(start + " reaches 1 in " + steps + " steps");
    }
}
27 reaches 1 in 111 steps

How it works: a perfect while-loop problem: nobody knows the number of steps in advance. Values can climb high before falling (27 goes past 9,000), so we use long to be safe from overflow.

P8Medium

Guess the number in the fewest tries

A secret number is between 1 and 100. Each guess is answered “higher” or “lower”. Always guess the middle of the remaining range, and print each guess and the number of tries.

Input
secret = 37
Expected output
Guesses: 50 25 37
Found in 3 tries
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int secret = 37;
        int low = 1, high = 100, tries = 0;
        System.out.print("Guesses:");
        while (low <= high) {
            int guess = (low + high) / 2;
            tries++;
            System.out.print(" " + guess);
            if (guess == secret) {
                break;
            } else if (guess < secret) {
                low = guess + 1;      // answer was "higher"
            } else {
                high = guess - 1;     // answer was "lower"
            }
        }
        System.out.println();
        System.out.println("Found in " + tries + " tries");
    }
}
Guesses: 50 25 37 Found in 3 tries

How it works: this is binary search. Each guess halves the remaining range, so any number from 1 to 100 is found in at most 7 tries (27 = 128). The loop runs while the range is non-empty and stops early with break when found.

P9Business problem

ATM PIN with 3 attempts

An ATM allows 3 PIN attempts. The entered PINs for one session are given in order. Print “Access granted on attempt k”, or “Card blocked” if all 3 attempts fail.

Input
correct PIN = 4321
entered = 1111, 2580, 4321
Expected output
Attempt 1: wrong PIN
Attempt 2: wrong PIN
Access granted on attempt 3
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        final int CORRECT_PIN = 4321;
        final int MAX_ATTEMPTS = 3;
        int[] entered = {1111, 2580, 4321};   // what the customer typed

        int attempt = 0;
        boolean granted = false;
        do {
            int pin = entered[attempt];
            attempt++;
            if (pin == CORRECT_PIN) {
                granted = true;
            } else {
                System.out.println("Attempt " + attempt + ": wrong PIN");
            }
        } while (!granted && attempt < MAX_ATTEMPTS);

        if (granted) {
            System.out.println("Access granted on attempt " + attempt);
        } else {
            System.out.println("Card blocked");
        }
    }
}
Attempt 1: wrong PIN Attempt 2: wrong PIN Access granted on attempt 3

How it works:

  1. do-while fits because the customer must be asked at least once.
  2. The loop has two reasons to stop, combined with &&: success, or running out of attempts.
  3. After the loop, the granted flag tells us why it stopped. Change the last PIN to 9999 to see “Card blocked”.
  4. Real ATMs never store or compare plain PINs like this; the card and bank verify them securely. The loop logic is the same, though.
P10Business problem

When will the fixed deposit double?

A customer invests ₹50,000 in a fixed deposit at 7% per year, compounded yearly. How many years until it reaches at least ₹1,00,000, and what will it be worth then? (Compare with the “Rule of 72” estimate: 72 ÷ 7 ≈ 10.3 years.)

Input
amount = 50000, rate = 7%,
target = 100000
Expected output
Doubles after 11 years
Value then: Rs 105242.60
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        double amount = 50_000;
        double ratePercent = 7;
        double target = 100_000;
        int years = 0;
        while (amount < target) {
            amount += amount * ratePercent / 100;   // one year of interest
            years++;
        }
        System.out.println("Doubles after " + years + " years");
        System.out.printf("Value then: Rs %.2f%n", amount);
    }
}
Doubles after 11 years Value then: Rs 105242.60

How it works:

  1. Each pass adds one year's interest on the current amount: that's compounding.
  2. After 10 years the amount is about ₹98,358, just short; year 11 takes it past the target. The Rule of 72 (≈ 10.3 years) is a good mental estimate.
  3. The loop condition matches the business question exactly: “keep going while it's below the target”.
  4. Real deposit calculations follow the bank's rules (quarterly compounding, TDS) and use BigDecimal for exact money.

Real-world scenario questions (asked in company interviews)

Loops that run “until something happens” are where systems hang and burn CPU. Decide your answer first, then open the model answer.

Logistics · background job1–3 years

A waiting loop that uses 100% CPU

A job waits for a file to arrive from a partner with while (!Files.exists(path)) { }. The ops team reports one CPU core stuck at 100% for hours whenever the partner is late. What's wrong and what would you do?

The interviewer is checking: do you recognise busy waiting and know better alternatives?

Show a strong answer

This is busy waiting: the empty loop checks the file system millions of times a second without pausing.

  • Sleep between checks (e.g. Thread.sleep(30_000)), ideally with a growing delay, and a maximum wait time after which the job alerts someone.
  • Better: react to events instead of polling: Java's WatchService for file system changes, or have the partner send a message or API call when the file is ready.
  • Add monitoring so late files are visible, not just a hot CPU.

Avoid: an empty while body that waits for something external.

Fintech · API integration1–3 years

Downloading transactions never finishes

A job fetches bank transactions page by page with while (cursor != null) { page = api.fetch(cursor); … cursor = page.next(); }. One night the partner API had a bug and kept returning the same cursor. The job ran for 9 hours and filled the disk with duplicates. How would you make the loop safe?

The interviewer is checking: do you defend loops that depend on external systems?

Show a strong answer
  • Detect lack of progress: if the new cursor equals the previous one (or a page returns zero items), stop and raise an alert.
  • Add a safety limit: a maximum number of pages or a time budget, beyond which the job stops and alerts.
  • Make writes idempotent (e.g. upsert by transaction ID), so repeated pages don't create duplicates.
  • Log progress per page so you can resume from the last good cursor.

Avoid saying: “The partner's API should be correct.” Our code must protect itself.

E-commerce · message queue1–3 years

One bad order blocks all the others

An order processor runs while (!queue.isEmpty()) { Order o = queue.poll(); try { process(o); } catch (Exception e) { queue.add(o); } }. One order has corrupted data and always fails. Soon the worker spends all its time retrying it, and other orders are delayed. What's the fix?

The interviewer is checking: do you know about poison messages, retry limits and dead-letter queues?

Show a strong answer

The corrupted order is a poison message: it can never succeed, but the loop retries it forever.

  • Track a retry count per message; after a few attempts (with a delay between them), stop retrying.
  • Move it to a dead-letter queue where people can inspect and fix it, and raise an alert.
  • Separate failures that can succeed later (a timeout) from ones that can't (invalid data), and only retry the first kind.

Avoid: silently dropping the order. Someone paid for it.

Banking · kiosk softwareFresher

The menu that shows up twice

A passbook-printing kiosk shows its menu with this code: showMenu(); int choice = read(); while (choice != 4) { handle(choice); showMenu(); choice = read(); }. A reviewer says it works but suggests a do-while. Why might do-while be clearer here?

The interviewer is checking: do you know when “at least once” is the natural shape of a loop?

Show a strong answer

The menu must be shown and read at least once. With while, the “show and read” code is written twice (before the loop and at the end of it), and the two copies can drift apart when someone edits one.

  • With do-while it's written once: do { showMenu(); choice = read(); if (choice != 4) handle(choice); } while (choice != 4);
  • Add input validation and a timeout, so an abandoned kiosk returns to the home screen.

Avoid saying: “Both work, so it doesn't matter.” Duplicated code is a maintenance risk.