Skip to content

Chapter 5 of 37

Loops

Repeat work with for, while, do-while, enhanced for, break, and continue.

28 minutes 10 quick checksBy Subha Prasad
Lesson 5 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Use for for counting, while for condition-driven repetition, and do-while when the body must run once. Enhanced for traverses arrays and Iterable values without indexing.

Safe iteration

int[] values = {2, 4, 6};
int total = 0;
for (int value : values) {
    total += value;
}

for (int i = 0; i < values.length; i++) {
    if (values[i] == 0) continue;
    if (values[i] < 0) break;
}

State the loop invariant, verify empty and boundary cases, and ensure each iteration progresses. break exits the nearest loop; continue advances it. Labels can target an outer loop but often signal logic that should be extracted. Do not structurally modify most collections inside enhanced for; use an iterator’s supported removal or a bulk operation. Nested full-size loops usually multiply complexity, so consider sets, maps, or stream operations when they express a more efficient algorithm.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes for loop?
Which Java term matches this description: A loop combining initialization, condition, and update.
Which statement best describes while loop?
Which Java term matches this description: A loop that tests its condition before every iteration.
Which statement best describes do-while loop?
Which Java term matches this description: A loop that executes its body at least once.
Which statement best describes enhanced for?
Which Java term matches this description: A loop that visits array or Iterable elements without an explicit index.
Which statement best describes continue?
Which Java term matches this description: A statement that skips to the next loop iteration.

0 of 10 checks passed

Your progress is saved on this device.