Lesson 18 / 140
লিখিত lesson · 13 মিনিট

While and Do-While Loops

Use `while` and `do-while` when the number of repetitions is unknown, for input validation, sentinel values and menu loops.

Preview

আপনি একটি free preview lesson দেখছেন।

Lesson Overview

A for loop is generally useful when the number of repetitions is known in advance. However, in many situations, we do not know beforehand how many times a loop will run: keep asking until the user types a valid age, keep showing a menu until the user chooses Exit, keep reading numbers until a special stop value arrives.

For this kind of condition-controlled repetition, Java provides while and do-while loops. They are what make a console program interactive, and they are also the easiest loops to get stuck in forever, so we will look closely at what makes them stop.

Learning Objectives

After completing this lesson, you will be able to:

  • Explain the execution flow of a while loop
  • Run a loop while a condition remains true
  • Write a counter-controlled while
  • Create an input validation loop
  • Use a sentinel value
  • Use do-while
  • Understand at-least-once execution
  • Create a simple menu loop
  • Choose an appropriate loop among for, while, and do-while
  • Identify common causes of infinite loops

What Is a while Loop?

while is a condition-controlled loop. The loop body executes while the condition remains true. Syntax:

java
while (condition) {
    // Repeated statements
}

For example:

java
int number = 1;
while (number <= 5) {
    System.out.println(number);
    number++;
}

Output:

text
1
2
3
4
5

How Does while Work?

The execution flow is:

  1. The condition is checked
  2. If the condition is true, the body executes
  3. After the body finishes, the condition is checked again
  4. When the condition becomes false, the loop ends

For a loop that counts to 3:

java
int number = 1;
while (number <= 3) {
    System.out.println(number);
    number++;
}

The flow is:

text
number = 1
1 <= 3 → true
Print 1
number becomes 2

2 <= 3 → true
Print 2
number becomes 3

3 <= 3 → true
Print 3
number becomes 4

4 <= 3 → false
Stop

while Is Entry-Controlled

A while loop checks its condition before executing the body:

java
int number = 10;
while (number < 5) {
    System.out.println(number);
}

Here, 10 < 5 is false from the beginning. Therefore, the body does not execute even once.

Counter-Controlled while

A while loop can count just like a for loop, but the three parts are written separately. In the first example, the initialization is int number = 1; before the loop, the condition is number <= 5, and the update is number++; at the end of the body. Forgetting that last line is the most common while bug.

Backward Counting

java
int number = 5;
while (number >= 1) {
    System.out.println(number);
    number--;
}

Output:

text
5
4
3
2
1

Input Validation with while

Suppose a valid age is 0 to 150. If the user enters an invalid age, we want to ask again:

java
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your age: ");
        int age = Integer.parseInt(scanner.nextLine().strip());

        while (age < 0 || age > 150) {
            System.out.println("Invalid age");
            System.out.print("Enter an age between 0 and 150: ");
            age = Integer.parseInt(scanner.nextLine().strip());
        }

        System.out.println("Valid age: " + age);

        scanner.close();
    }
}

The Value Used by the Condition Must Be Updated

Wrong:

java
int age = -10;
while (age < 0 || age > 150) {
    System.out.println("Invalid age");
}

age never changes, so the condition remains true and the result is an infinite loop. The loop body must provide an opportunity for the condition to change.

Non-Blank Input Validation

java
System.out.print("Enter your name: ");
String name = scanner.nextLine().strip();
while (name.isBlank()) {
    System.out.println("Name is required");
    System.out.print("Enter your name: ");
    name = scanner.nextLine().strip();
}

If the input is blank, the loop displays the prompt again.

Sentinel Values

A sentinel is a special value that signals the end of an input sequence. In a prompt like Enter -1 to stop, -1 is the sentinel. This program adds numbers until the sentinel arrives:

java
import java.util.Scanner;

public class Main {

    static final int SENTINEL = -1;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int total = 0;

        System.out.print("Enter a number or -1 to stop: ");
        int number = Integer.parseInt(scanner.nextLine().strip());

        while (number != SENTINEL) {
            total += number;
            System.out.print("Enter a number or -1 to stop: ");
            number = Integer.parseInt(scanner.nextLine().strip());
        }

        System.out.println("Total: " + total);

        scanner.close();
    }
}

Possible interaction:

text
Enter a number or -1 to stop: 10
Enter a number or -1 to stop: 20
Enter a number or -1 to stop: 5
Enter a number or -1 to stop: -1
Total: 35

The sentinel is a termination signal, so it is not added to the total.

What Is a do-while Loop?

A do-while loop executes the body first, then checks the condition. Syntax:

java
do {
    // Repeated statements
} while (condition);

The semicolon ; at the end is required. A basic example:

java
int number = 1;
do {
    System.out.println(number);
    number++;
} while (number <= 5);

Output:

text
1
2
3
4
5

do-while Is Exit-Controlled

A do-while loop checks the condition after the body executes. Therefore, the body executes at least once:

java
int number = 10;
do {
    System.out.println(number);
} while (number < 5);

Output:

text
10

Even though the condition is false from the beginning, the body executes once.

while vs. do-while

  • while checks the condition first, so the body executes zero or more times.
  • do-while executes the body first and checks the condition afterward, so the body executes at least once.

Input Validation with do-while

Input must be taken at least once. For this flow, do-while is natural:

Diagram আঁকা হচ্ছে…

For example:

java
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int mark;

        do {
            System.out.print("Enter a mark between 0 and 100: ");
            mark = Integer.parseInt(scanner.nextLine().strip());
            if (mark < 0 || mark > 100) {
                System.out.println("Invalid mark");
            }
        } while (mark < 0 || mark > 100);

        System.out.println("Valid mark: " + mark);

        scanner.close();
    }
}

Menu with do-while

A menu must usually be shown at least once. Therefore, do-while is useful here:

java
import java.util.Scanner;

public class Main {

    static final int VIEW_COURSES = 1;
    static final int CREATE_COURSE = 2;
    static final int EXIT = 3;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int option;

        do {
            System.out.println();
            System.out.println("1. View courses");
            System.out.println("2. Create course");
            System.out.println("3. Exit");
            System.out.print("Choose an option: ");
            option = Integer.parseInt(scanner.nextLine().strip());

            switch (option) {
                case VIEW_COURSES -> System.out.println("Loading courses");
                case CREATE_COURSE -> System.out.println("Opening course form");
                case EXIT -> System.out.println("Goodbye");
                default -> System.out.println("Invalid option");
            }
        } while (option != EXIT);

        scanner.close();
    }
}

The menu repeats until the user selects 3. The project in lesson 1.20 combines a menu loop like this one with input validation loops and the grade rules from lesson 1.15.

for, while, or do-while?

LoopGood Choice When
forRepetition count or range is known in advance
whileRepeat while a condition remains true
do-whileThe body must execute at least once

For example:

  • Use for to print 1 to 100, read exactly 5 marks, or traverse String indexes.
  • Use while to repeat until valid input is received, read input until a sentinel is received, or process until a condition changes.
  • Use do-while to show a menu at least once, read input at least once, or ask whether the user wants to continue.

The Same Counter Loop: for vs. while

for:

java
for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

Equivalent while:

java
int number = 1;
while (number <= 5) {
    System.out.println(number);
    number++;
}

For counter-based fixed repetition, for is more concise. For condition-driven flow, while is more natural.

Infinite while Loop

Here is an intentional infinite loop:

java
while (true) {
    System.out.println("Running");
}

The condition is always true, so this loop does not terminate by itself.

Loop Trace

An accumulator works in a while loop just as in a for loop. Writing down the values for each iteration shows how it grows:

java
int number = 1;
int total = 0;
while (number <= 3) {
    total += number;
    number++;
}
Iterationnumber beforetotal afternumber after
1112
2233
3364

Final values:

text
number = 4
total = 6

Predict the Result

Question 1

java
int count = 10;
do {
    System.out.println(count);
    count++;
} while (count < 5);

What does this print?

Answer

10. A do-while runs its body once before checking the condition. Only then does 11 < 5 turn out false.

Question 2

java
int count = 10;
while (count < 5) {
    System.out.println(count);
    count++;
}
System.out.println("Done");

What does this print?

Answer

Done. A while checks the condition first. 10 < 5 is false, so the body never runs.

Question 3

java
int value = 1;
while (value < 100) {
    value *= 3;
}
System.out.println(value);

What does this print?

Answer

243. The value goes 1, 3, 9, 27, 81, 243. The condition is checked only at the start of each iteration, so the last multiplication takes the value past 100.

Question 4

java
int count = 3;
while (count-- > 0) {
    System.out.print(count + " ");
}

What does this print?

Answer

2 1 0 . Postfix count-- compares the old value with 0 and then decreases it, so the body already sees the smaller value. The check 0 > 0 ends the loop.

Common Mistakes

Missing or Wrong Update

A loop whose body never changes the value in its condition runs forever: a counter without number++, or an input loop that prints "Name is required" without reading a new name (see The Value Used by the Condition Must Be Updated). Updating in the wrong direction, number-- in a loop that waits for number <= 5 to become false, has the same effect: the counter moves away from the end.

Extra Semicolon

Wrong:

java
while (number <= 5); {
    number++;
}

The semicolon creates an empty loop body. Because number never changes inside that empty body, the loop never ends. Correct:

java
while (number <= 5) {
    number++;
}

Assignment Instead of Boolean Logic

Wrong:

java
boolean active = false;
while (active = true) {
    System.out.println("Running");
}

Here, true is being assigned. Preferred:

java
while (active) {
    System.out.println("Running");
}

Forgetting the Semicolon After do-while

Unlike while, a do-while loop ends with a semicolon: } while (number <= 5);. Without it, the code does not compile (';' expected).

Updating at the Wrong Position

java
int number = 1;
while (number <= 5) {
    number++;
    System.out.println(number);
}

Output:

text
2
3
4
5
6

If the expected output is 1–5:

java
while (number <= 5) {
    System.out.println(number);
    number++;
}

Practice Exercise 1: Count 1 to 10

Solutions: lesson 1.25.

Use while to print from 1 to 10.

Practice Exercise 2: Reverse Countdown

Print from 10 down to 1.

Practice Exercise 3: Even Numbers

Use while to print even numbers from 2 to 20.

Practice Exercise 4: Sum

Use while to calculate the sum from 1 to 100. Expected:

text
5050

Practice Exercise 5: Valid Age

Repeat the input until the user enters a valid age. The valid range is 0 to 150.

Practice Exercise 6: Valid Mark with do-while

Repeat the prompt until a valid mark in the 0–100 range is entered.

Practice Exercise 7: Non-Blank Name

If the user provides blank input, ask for the name again.

Practice Exercise 8: Sentinel Total

The user enters numbers, and input should end when the user enters -1. Calculate the total of all entered numbers except the sentinel.

Practice Exercise 9: Menu

Menu:

text
1. View courses
2. Create course
3. Exit

Use do-while to repeat the menu until the user exits.

Practice Exercise 10: Fix the Infinite Loop

java
int number = 1;
while (number <= 5) {
    System.out.println(number);
}

Explain the problem and fix it.

Practice Exercise 11: Choose the Loop

Choose for, while, or do-while for each situation:

  1. Print exactly 10 times
  2. Show a menu until the user exits
  3. Repeat until valid input is received
  4. Traverse all indexes of a String
  5. Read exactly 5 marks
  6. Read numbers until a sentinel is received

Knowledge Check

Question 1

What is while?

Question 2

When is the while condition checked?

Question 3

If the condition is false from the beginning, how many times does the body execute?

Question 4

What can happen if the counter is not updated?

Question 5

What is a sentinel value?

Question 6

Should a sentinel be processed as normal data?

Question 7

When is the do-while condition checked?

Question 8

What is the minimum number of times a do-while body executes?

Question 9

Is a semicolon required at the end of do-while?

Question 10

Why is do-while useful for input validation?

Question 11

What is the main difference between for and while?

Question 12

Why is do-while useful for menus?

Question 13

What does while (true) create?

Question 14

What can an incorrect update direction cause?

Question 15

Which loop is entry-controlled?

Question 16

Which loop is exit-controlled?

Knowledge Check Answers

Answer 1

while is a loop that repeats a block of code while a condition remains true.

Answer 2

Before every iteration.

Answer 3

Zero times.

Answer 4

It can cause an infinite loop.

Answer 5

A special value used as a signal to end an input sequence.

Answer 6

No, if the sentinel is used only as the termination signal.

Answer 7

After the body executes.

Answer 8

At least once.

Answer 9

Yes.

java
} while (condition);

Answer 10

Because input must be read at least once before its validity can be checked.

Answer 11

for is concise for fixed or counter-based repetition. while is more natural for condition-controlled repetition.

Answer 12

Because the menu normally needs to be displayed at least once.

Answer 13

An infinite loop.

Answer 14

The counter can move away from making the condition false, causing the loop not to terminate.

Answer 15

while.

Answer 16

do-while.

Lesson Summary

  • A while loop checks its condition before every iteration, so its body can execute zero times. It is entry-controlled.
  • A do-while loop executes its body first and checks the condition afterward, so its body executes at least once. It is exit-controlled.
  • The loop body must change the value used by the condition; otherwise the loop becomes infinite.
  • A while loop is a natural fit for input validation, where you do not know how many attempts are needed.
  • A sentinel value, such as -1, signals the end of input and is not processed as normal data.
  • A do-while loop suits menus and prompts that must be shown at least once.
  • Use for when the repetition count or range is known, while when a condition controls the repetition, and do-while when the body must run at least once.

আগে ভাবুন

শীঘ্রই আসছে

Checkpoint প্রশ্ন, যেখানে lesson উত্তর দেখানোর আগে আপনাকে একটি উত্তর বেছে নিতে হবে।