Courseiva
1Z0-811Chapter 7 of 16Objective 2.4

Repetition with Loops (for, while, do-while)

How do you make a computer repeat an action without writing the same code over and over? This is the problem that loops solve in Java. For the 1Z0-811 exam, understanding when and how to use for, while, and do-while loops is essential because you will be tested on their syntax, their behaviour, and the subtle differences that determine which one to choose in a given situation.

12 min read
Beginner
Updated Jul 23, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture Repetition with Loops (for, while, do-while)

The Bakery Order Queue Analogy

A bakery's order queue is a system of repetition controlled by specific conditions. The baker has a queue of order tickets, each listing items to prepare. The baker works through this queue using one of three repetition methods, mirroring how a computer program uses different loop structures.

When the baker knows exactly how many items are on a ticket, she uses a fixed repetition. For example, a ticket for twelve identical cookies means she follows the same cookie-preparation steps exactly twelve times. This is exactly how a for loop works: the programmer specifies a known number of repetitions upfront.

Sometimes a baker faces an unknown stack of orders. She must keep preparing orders as long as the shop is open. She checks before each new order: 'Is the shop still open?' If yes, she takes one order and starts working. She repeats this check-and-work cycle until the closing time condition becomes false. This is a while loop: the condition is checked before each repetition, so it might never execute if the shop is already closed.

Finally, there is the urgent special-order scenario. A customer places a unique cake order that must be prepared at least once. The baker starts preparing the cake immediately, and only after finishing that first batch does she ask the customer if they want another. This is a do-while loop: the loop body executes at least once before the condition is checked.

Each method has its correct use. Choosing the wrong one leads to burnt cookies, wasted ingredients, or unhappy customers — just as choosing the wrong loop in code can lead to bugs, infinite loops, or skipped logic.

How It Actually Works

A loop is a programming construct that repeats a block of code as long as a certain condition remains true. Think of it as telling the computer: 'Keep doing this task until I tell you to stop.' Without loops, you would have to copy and paste the same code for every repetition. That would be tedious, error-prone, and impossible if you don't know in advance how many repetitions you need.

Java offers three types of loops: for, while, and do-while. Each has a different syntax and is suited for different scenarios.

The for loop is used when you know exactly how many times you want the code to repeat. Its structure has three parts separated by semicolons inside parentheses: initialisation, condition, and update. For example: for(int i = 0; i < 10; i++) { System.out.println(i); }. This initialises a counter variable i to 0, checks if i is less than 10, and if true, runs the code inside the braces. After each run, it increments i by one. The loop stops when i becomes 10. The for loop is compact and clearly shows the loop's start, end, and step in one line.

The while loop is used when you want to repeat based on a condition that might change during execution, but you do not necessarily have a fixed number of repetitions. Its syntax is: while(condition) { // code }. The condition is evaluated before each iteration. If the condition is false at the start, the loop body never executes. This is known as a zero-or-more-times loop. For example, reading user input until they type 'quit': String input = scanner.next(); while(!input.equals("quit")) { process(input); input = scanner.next(); }.

The do-while loop is similar to the while loop, but with a crucial difference: the condition is checked after the loop body executes. This guarantees that the loop body runs at least once. Its syntax is: do { // code } while(condition);. Notice the semicolon after the while condition. A common use case is displaying a menu to a user, processing their choice, and then asking if they want to continue. You want the menu displayed at least once before checking their response.

Nested loops occur when you place one loop inside the body of another. The inner loop completes all its iterations for each single iteration of the outer loop. For example, a for loop iterating over rows can contain a for loop iterating over columns to print a rectangle. The outer loop controls the rows, the inner loop controls the columns. Nested loops are common when working with multi-dimensional data like tables or matrices.

Crucial concepts for the exam include loop control variables, infinite loops (when the condition never becomes false), and loop scoping (variables declared inside the loop body are not accessible outside it). The break statement can exit a loop immediately, while continue skips the rest of the current iteration and moves to the next one.

Understanding which loop to use comes with practice. As a rule of thumb:

Use a for loop when you know the exact number of iterations (e.g., iterating over an array from index 0 to length-1).

Use a while loop when the number of iterations is unknown and you might need to skip the loop entirely (e.g., waiting for a resource to become available).

Use a do-while loop when the loop body must execute at least once (e.g., presenting a menu that always appears once).

A flowchart comparing the decision and execution flow of for, while, and do-while loops in Java.

Walk-Through

1

Identify the repetition need

Before writing any loop, determine what action needs repeating and under what condition it should stop. For example, you want to print all items in a list. The action is 'print one item', and the stop condition is 'no more items left'. This step defines the loop's purpose.

2

Choose the loop type

Based on the need, select for, while, or do-while. If you know the exact count, choose for. If you might not execute at all, choose while. If you must execute at least once, choose do-while. This decision affects the code structure and behaviour.

3

Write the loop header

For a for loop, write for(initialisation; condition; update). For a while loop, write while(condition). For a do-while, write do { } while(condition);. Ensure the syntax is exact, including the semicolon in do-while. The header sets up the repetition rules.

4

Write the loop body

Inside the braces, write the code that should repeat. This can include multiple statements. In a nested loop, the body may contain another entire loop. The body defines what happens each iteration. Ensure that the body eventually influences the condition (e.g., decrements a counter) to avoid infinite loops.

5

Test the loop boundaries

Mentally trace the loop with the smallest and largest expected inputs. Check the first iteration, a middle iteration, and the last iteration. Verify that the condition becomes false at the correct time. This catches off-by-one errors and infinite loops before runtime.

6

Run and debug

Execute the code and observe the output. If the output is wrong, use print statements inside the loop to trace variable values each iteration. This helps identify logic errors in the condition or update statements. Fix errors and re-test until the loop behaves as expected.

What This Looks Like on the Job

An IT professional writing code for an e-commerce website uses loops constantly. Consider a developer building a shopping cart checkout system. The system needs to calculate the total price of all items in a user's cart. The number of items varies per user, so the developer cannot hardcode individual lines for each item. Instead, they use a for loop to iterate through the cart's item list.

Step by step, the developer writes code that:

Gets the list of items from the user's session.

Initialises a variable totalPrice to 0.

Uses a for loop: for(int i = 0; i < cartItems.size(); i++) { totalPrice = totalPrice + cartItems.get(i).getPrice(); }

The loop runs exactly as many times as there are items, adding each price to the total.

Another scenario involves a system administrator who writes a script to check whether all servers in a data centre are responsive. The admin uses a while loop to ping each server one by one. The condition checks if there are more servers in the list. If the list is empty, the loop body never runs — that is fine because there is nothing to check. The admin might also use a do-while loop if they must start pinging immediately and only ask for confirmation to stop after the first ping.

In game development, nested loops are used frequently. A developer creating a 2D grid-based game uses an outer for loop for the rows and an inner for loop for the columns. For each row, the inner loop iterates through each column to draw the tile at that position. If the grid is 10 by 10, the inner loop runs 100 times in total (10 rows times 10 columns).

Financial applications use loops to process transactions. A while loop reads transactions from a queue until the queue is empty. Inside the loop, each transaction is validated, processed, and logged. The loop ensures that all transactions are handled, regardless of how many there are.

IT professionals must also be cautious about infinite loops. If a loop's condition never becomes false, the program hangs or crashes. For example, forgetting to increment the counter in a while loop causes it to run forever. Real-world consequences include unresponsive software, server timeouts, and data corruption. Experienced developers always ensure that the loop's condition will eventually become false, either by updating a counter or by changing the controlling variable inside the loop body.

How 1Z0-811 Actually Tests This

The 1Z0-811 exam tests your ability to demonstrate the use of for, while, and do-while loops, including nested loops. The questions are predominantly multiple-choice and code-analysis style. You will be given a snippet of Java code containing a loop and asked to determine its output, identify whether it compiles, or choose the correct loop for a given scenario.

Exam topics and trap patterns you must know:

Recognising the syntax of each loop: The for loop requires three parts in parentheses separated by semicolons. The while loop has a single boolean condition. The do-while loop ends with a semicolon after the while condition. Forgetting the semicolon in a do-while is a common syntax error they test.

Infinite loops: They love to present a loop where the update statement is missing or the condition never changes. You must identify that the loop will run forever and thus the program will not terminate.

Loop scope: Variables declared inside the for loop initialisation (e.g., int i) are only accessible within the loop body. Questions may test whether a variable declared in the for loop can be used after the loop. It cannot.

Off-by-one errors: A loop that runs one time too many or one time too few. For example, for(int i = 0; i <= 5; i++) runs 6 times (0 through 5), while i < 5 runs 5 times. Pay close attention to the comparison operator.

Nested loop execution count: They may ask how many times a print statement executes. For an outer loop running n times and an inner loop running m times, the total is n * m.

The difference between while and do-while: A do-while loop always executes its body at least once, while a while loop may execute zero times. A question may describe a scenario where zero executions are required, making while the correct answer.

Using break and continue: break exits the innermost loop entirely. continue skips the rest of the current iteration and jumps to the next. Exam questions may show a loop with a break inside an if statement and ask what prints.

Loop control variable modification: If you modify the loop counter inside the loop body, it can affect the number of iterations. Questions might show code that changes i inside a for loop and ask for the output.

To prepare, practise writing each loop type from memory. Trace through code line by line on paper, recording the value of variables after each iteration. This skill is directly tested. Also, study the common patterns that appear: iterating over an array, reading input until a sentinel value, and building patterns with nested loops (like triangles or rectangles).

Key Takeaways

A for loop is used when the number of iterations is known in advance; it has initialisation, condition, and update parts in one line.

A while loop checks its condition before executing the body, so it may run zero times if the condition is initially false.

A do-while loop always executes its body at least once because the condition is checked after the first iteration.

Nested loops multiply the total iterations: if an outer loop runs N times and an inner loop runs M times, the inner body runs N * M times total.

The loop control variable declared inside a for loop's initialisation has scope limited to the loop body and cannot be used outside it.

An infinite loop occurs when the loop condition never becomes false; the most common cause is forgetting to update the loop control variable.

The break statement exits the currently innermost loop immediately, while the continue statement skips the rest of the current iteration.

Choosing the correct loop type is a design decision based on whether the loop must run at least once and whether the count is known upfront.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

for loop

Initialisation, condition, and update are all written in one line

Best used when the number of iterations is known beforehand

Loop variable is often declared inside the loop header

while loop

Only the condition is in the parentheses; initialisation and update are separate

Best used when the number of iterations depends on a changing condition

Loop variable is typically declared before the loop

while loop

Condition is checked before the loop body executes

Loop body may execute zero times

Syntax: while(condition) { }

do-while loop

Condition is checked after the loop body executes

Loop body always executes at least once

Syntax: do { } while(condition); (note the semicolon)

break

Exits the innermost loop entirely

Execution jumps to the code after the loop

Useful for early termination when a condition is met

continue

Skips the rest of the current iteration

Execution jumps directly to the next iteration (update and condition check)

Useful to skip invalid data without breaking the loop

for loop with counter i from 0 to 4

Loop runs 5 times: i = 0, 1, 2, 3, 4

Common pattern for iterating over array indices (0-based)

Condition: i < 5

for loop with counter i from 1 to 5

Loop runs 5 times: i = 1, 2, 3, 4, 5

Common pattern for counting or iterating when you need values starting at 1

Condition: i <= 5

Watch Out for These

Mistake

A while loop always runs at least once.

Correct

A while loop checks its condition before executing the body, so it might run zero times. Only a do-while loop guarantees at least one execution.

This mistake comes from mixing up while with do-while. The similar names and the fact that both repeat until a condition is false cause confusion.

Mistake

The loop counter variable in a for loop can be used after the loop ends.

Correct

If the variable is declared inside the for loop initialisation (for(int i=0; ...)), its scope is limited to the loop body. It cannot be accessed after the loop.

Beginners see the variable defined in the same line as the loop and assume it has broader scope, similar to variables declared before the loop.

Mistake

A for loop and a while loop are interchangeable in all situations.

Correct

A for loop is best when the number of iterations is known in advance. A while loop is better when the number of iterations depends on a dynamic condition. Using the wrong type can make code harder to read and maintain.

Both loops can technically be written to achieve the same result, so beginners think there is no difference. They miss the conceptual intent and readability advantages of each.

Mistake

Changing the loop control variable inside the loop body is a good practise.

Correct

Modifying the loop counter inside the loop body (e.g., i = i + 2 inside a for loop) is risky because it can make the loop unpredictable and hard to debug. It is generally discouraged.

New programmers think they can 'optimise' by skipping steps, but they often introduce bugs or infinite loops. The exam tests whether you can trace the modified flow.

Mistake

Nested loops always slow down a program, so they should be avoided.

Correct

Nested loops are necessary for processing multi-dimensional data like tables, grids, or matrices. They are not inherently bad; they are a tool for solving certain problems. Performance concerns depend on the data size and algorithm.

Beginners hear that nested loops increase complexity and assume they are harmful. They miss that many real-world tasks require nested iteration.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

When should I use a for loop instead of a while loop?

Use a for loop when you know the exact number of iterations in advance, such as when iterating over an array from index 0 to length-1. Use a while loop when the number of iterations depends on a condition that might change inside the loop.

What happens if the condition in a while loop is false from the start?

If the condition is false when the while loop is first reached, the loop body never executes. Execution jumps to the code after the loop. This is a key difference from a do-while loop, which always runs at least once.

Can I use a for loop to iterate through a list where the size changes?

You can, but it is risky. If you add or remove items from the list while iterating, the loop may skip items or cause an exception. It is safer to use an iterator or a while loop that checks the condition each time.

How do I write a nested for loop to print a multiplication table?

Use an outer loop for rows (1 to 10) and an inner loop for columns (1 to 10). Inside the inner loop, print the product of the row and column numbers. After the inner loop, print a newline to move to the next row.

What is an infinite loop and how can I avoid it?

An infinite loop is a loop whose condition never becomes false, causing the program to run forever. Avoid it by ensuring that the loop's condition is updated each iteration (e.g., by incrementing a counter or changing a boolean flag) so it eventually becomes false.

Is it possible to exit a loop from inside the body?

Yes, you can use the break statement to exit the innermost loop immediately. This is useful when you find what you are looking for and want to stop early. The continue statement skips the rest of the current iteration and starts the next one.

Terms Worth Knowing

Keep going

You've finished Repetition with Loops (for, while, do-while). Continue through the 1Z0-811 study guide to build a complete picture of the exam.

Done with this chapter?