← Chapter 4 — Decision Making & Loops

18. Loops: while, do-while & for

mixed

Description

Loops repeat code while a condition allows it. Use them for counting, processing arrays, and retrying an action.

Choose the loop that shows your intent. A for loop suits a known count, while a while loop suits repetition that depends on a changing condition.

Subtopics

while and do-while

Description

while checks before the body; do-while checks after.

Explanation

A do-while body always runs at least once.

Example

int i = 1;
while (i <= 3) { i++; }

for loop

Description

for keeps setup, condition, and update together.

Explanation

It is ideal for a counter with a clear range.

Example

for (int i = 1; i <= 3; i++) { }

Explanation

Every loop needs a path toward stopping. Update the counter or state deliberately to avoid an accidental infinite loop.

Example

public class LoopDemo {
    public static void main(String[] args) {
        for (int lesson = 1; lesson <= 3; lesson++) {
            System.out.println("Completed lesson " + lesson);
        }
    }
}

Key points

  • while may run zero times.
  • do-while runs at least once.
  • for is useful for counted repetition.

Video

Open video

Open reference