SECTION 1
Historical Context & Motivation
Computers are fundamentally about doing repetitive work fast—but early programmers had to figure out how to tell machines to repeat instructions. The concept of a loop became one of the most important ideas in all of programming. Before high-level languages like Java existed, programmers wrote goto statements in assembly language to jump backward in code and re-execute instructions. This worked, but it created tangled, hard-to-read programs that developers called spaghetti code.
1949 • Assembly Language Loops
1966 • Structured Programming Theorem
1972 • C Language Standardizes while
while and do-while loop syntax that Java would later adopt nearly unchanged.1995 • Java Inherits Loop Syntax
while and do-while loops as core control-flow tools.Structured programming replaced messy goto jumps with clean loop constructs. The central question this lesson addresses is: when should you use a while loop versus a do-while loop, and how do you write each one correctly? Understanding the difference will help you write cleaner, more intentional code.
SECTION 2
Core Principles & Definitions
Both while and do-while loops repeat a block of code as long as a boolean condition evaluates to true. They differ in one critical way: when the condition gets checked. Grasping this distinction is the key to choosing the right loop for any situation.
While Loop (Pre-Test)
false initially, the body executes zero times.Do-While Loop (Post-Test)
Loop Variable
false. Without updating it, you get an infinite loop.Boolean Condition
true or false. Common operators include <, >=, !=, and ==.Infinite Loop
false. The program runs forever (or until it crashes). This is the most common loop bug for beginners.KEY TAKEAWAY
while loop like checking the weather before you go outside—if it's storming, you stay in and never go out. A do-while loop is like going outside first and then checking the weather—you're already outside at least once no matter what.SECTION 3
Visual Explanation — Loop Flowcharts
Study the two flowcharts above carefully. In the left diagram (the while loop), the program hits the condition diamond first. If that condition is already false, the program takes the dashed path straight to "End" and the body never runs. In the right diagram (the do-while loop), the program enters the body immediately. Only after executing the body does the condition get evaluated. This is why a do-while loop always runs at least once.
SECTION 4
How While & Do-While Loops Work in Code
The while Loop Syntax
WHILE LOOP TEMPLATE
condition — a boolean expression evaluated before each iteration. loop body — the statements that repeat. update — code that changes the loop variable so the condition eventually becomes false.
Here is a concrete example that prints the numbers 1 through 5. The variable i starts at 1, and the loop continues as long as i <= 5. After printing, i++ increments i by 1 each time.
WHILE LOOP EXAMPLE
When i reaches 6, the condition 6 <= 5 is false, so the loop terminates.
The do-while Loop Syntax
DO-WHILE LOOP TEMPLATE
Note the semicolon after the closing parenthesis — this is required and easy to forget! The body runs first, then the condition is checked.
DO-WHILE LOOP EXAMPLE
This produces the same output as the while example. The difference appears when the condition is false from the start — the do-while body still runs once.
Watch Out: Infinite Loops!
i++), the condition never becomes false and the loop runs forever. Your program will freeze. If this happens, press Ctrl + C in your terminal to stop it.SECTION 5
Choosing While vs. Do-While
Knowing the syntax is only half the battle — you also need to know which loop to pick for a given situation. The decision comes down to one question: does the code inside the loop need to run at least once, regardless of the condition?
for loop (covered in another lesson). If the count is unknown and depends on a condition, ask whether the body must execute at least once. If yes, use do-while. If not necessarily, use while.Common Use Cases
| Scenario | Best Loop | Why |
|---|---|---|
| Reading from a file until end-of-file | while | The file might be empty, so you should check before reading. |
| Waiting for valid user input | do-while | You need to ask the user at least once before you can check if input is valid. |
| Searching through a list | while | The list could be empty; checking the condition first avoids errors. |
| Displaying a menu until the user quits | do-while | You need to show the menu at least once so the user can choose an option. |
| Counting down from a number | while | If the starting number is already 0, you don't want to print anything. |
Common scenarios and which loop fits best
SECTION 6
Worked Example — Input Validation with do-while
Let's walk through a realistic example. Imagine you're building a program that asks the user to enter an exam score between 0 and 100. If they type something out of range, you ask again. Since you must ask at least once, this is a perfect situation for a do-while loop.
Exam Score Validator
- 1
Step 1 — Declare Variables
We need aScannerobject for input and anintto hold the score.Scanner scanner = new Scanner(System.in);andint score; - 2
Step 2 — Write the do-while Loop
The loop body prompts the user and reads their input. The condition checks if the score is invalid (below 0 or above 100). If invalid, the loop repeats.do { System.out.print("Enter score (0-100): "); score = scanner.nextInt(); } while (score < 0 || score > 100); - 3
Step 3 — Trace Through an Example Run
Suppose the user types-5first. The body runs,scorebecomes −5. The condition-5 < 0 || -5 > 100istrue, so the loop repeats. The user then types85. The condition85 < 0 || 85 > 100isfalse, so the loop exits.Final value: score = 85 - 4
Step 4 — Use the Validated Score
After the loop, we knowscoreis guaranteed to be between 0 and 100 inclusive. We can safely use it.System.out.println("You entered: " + score);
Why Not a while Loop Here?
while loop, you'd need to initialize score to an invalid value (like −1) just to make the condition true on the first check. That's a workaround—do-while is cleaner because the intent is clear: ask first, then validate.SECTION 7
While vs. Do-While — Strengths & Limitations
| Feature | while | do-while |
|---|---|---|
| Condition check | Before each iteration (pre-test) | After each iteration (post-test) |
| Minimum executions | 0 times | 1 time |
| Semicolon after condition | No | Yes — required after the closing parenthesis |
| Readability | Condition is visible at the top—easy to see the guard | Condition is at the bottom—less immediately visible |
| Frequency in real code | Very common — the default choice for most loops | Less common — mainly for menus, input validation, and retry logic |
| Risk of infinite loop | Same risk — must update loop variable in body | Same risk — must update loop variable in body |
Side-by-side comparison of while and do-while loops
KEY TAKEAWAY
while loops appear far more often in Java code than do-while loops. Think of while as your default tool—like a regular screwdriver. The do-while is a specialty tool—like a ratchet—that you reach for only when you specifically need the "run at least once" guarantee, such as input validation or menu display.SECTION 8
Connecting to Advanced Concepts
Once you're comfortable with while and do-while, you'll encounter more advanced loop-related concepts in Java. Understanding the basics now prepares you to use tools like break, continue, nested loops, and even recursion later.
| What You Learned | What Comes Next |
|---|---|
while and do-while syntax | for loops and enhanced for-each loops for collections |
| Using a boolean condition to control repetition | Using break to exit a loop early and continue to skip an iteration |
| Single-level loops | Nested loops (a loop inside a loop) for grids, tables, and multi-dimensional data |
| Iterative repetition | Recursion — a method calling itself to solve sub-problems |
| Looping with simple counters | Using Iterator objects and Stream API for advanced data processing |
How while/do-while connects to future Java topics
The idea of condition-driven repetition is universal in programming. Whether you eventually learn Python, JavaScript, or any other language, you'll find equivalents to while loops everywhere. Mastering them in Java gives you a transferable skill that applies to virtually every programming language.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
while loop and a do-while loop? If a while loop's condition is false from the start, how many times does the body execute? What about a do-while loop in the same situation?Show answer
while loop is a pre-test loop — it checks the condition before the body runs. If the condition starts as false, the body executes zero times. A do-while loop is a post-test loop — it runs the body first, then checks the condition. So even if the condition is false from the start, the body still executes exactly one time.Question 2: BASIC CALCULATION
sum after the loop completes:
int sum = 0;
int n = 1;
while (n <= 4) {
sum += n;
n++;
}Show answer
Question 3: INTERMEDIATE
do-while loop that generates random integers between 1 and 10 (inclusive) and prints each one. The loop should stop when it generates the number 7. Use (int)(Math.random() * 10) + 1 to generate random numbers. Explain why do-while is the correct choice here.Show answer
int num;
do {
num = (int)(Math.random() * 10) + 1;
System.out.println(num);
} while (num != 7); A do-while loop is the correct choice because you need to generate a number before you can check whether it equals 7. You can't evaluate the condition without first producing a value. The body must run at least once to create the first random number.Question 4: APPLIED
while loop that determines how many years it takes for the balance to reach $0 or below. Print the number of years. Then explain: what would happen if you used a do-while loop instead, and would the result change?Show answer
int balance = 1000;
int years = 0;
while (balance > 0) {
balance -= 50;
years++;
}
System.out.println(years); After 20 iterations, balance reaches exactly $0 (which is not > 0), so the loop stops and prints 20. If you used a do-while loop with the same condition, the result would be the same because the initial condition (1000 > 0) is true, so both loops enter the body on the first pass. The difference would only appear if the starting balance were already $0 or negative — then the while loop would print 0, but the do-while would subtract $50 once and print 1.Question 5: CRITICAL THINKING
int x = 10;
while (x > 0) {
System.out.println(x);
x -= 3;
} First, trace through the loop and list all values printed. Then answer: could you rewrite this as a do-while loop and get the same output? Now suppose x started at 0 — would both versions still produce the same output? Justify your answer.Show answer
do { System.out.println(x); x -= 3; } while (x > 0); and get the same output because when x starts at 10, the condition is true initially, so both loops behave identically. However, if x started at 0, the while loop would print nothing (0 > 0 is false immediately), but the do-while loop would print 0 once before checking the condition. This demonstrates the fundamental difference: do-while always guarantees at least one execution.SUMMARY
Lesson Summary
Summary
Java provides two condition-driven loop constructs. The while loop is a pre-test loop that evaluates its boolean condition before each iteration — if the condition is false from the start, the body executes zero times. The do-while loop is a post-test loop that runs the body first and then checks the condition — guaranteeing at least one execution. Remember that do-while requires a semicolon after its closing parenthesis.
Use while as your default loop when repetition depends on a condition and the body might not need to run. Use do-while specifically when you need the body to execute before the first condition check, such as input validation or menu displays. Always include a loop variable update in the body to avoid infinite loops, and choose the right loop by asking: "Must this code run at least once?"