Loops: for, while, do-while

Site Admin · 11 Sep 2026 · 11 views

for Loop

A loop repeats a block while a condition holds. The classic counting loop:

for (int i = 1; i <= 5; i++) {
    System.out.println("Count " + i);
}

The three parts are initialisation, condition and update: for (start; condition; step).

while Loop

Use while when you do not know in advance how many times the loop will run.

int attempts = 0;
boolean correct = false;
while (!correct) {
    attempts++;
    if (attempts == 3) correct = true;
}
System.out.println("Stopped after " + attempts + " attempts");

do-while Loop

A do-while always runs its body at least once because the condition is checked at the end.

int value;
do {
    value = 8;
} while (value > 10); // false, but loop ran once
System.out.println(value); // 8

The Enhanced for Loop

Safely iterates over arrays and collections without index arithmetic:

int[] prices = {10, 20, 30};
int sum = 0;
for (int price : prices) {
    sum += price;
}
System.out.println("Total: " + sum); // 60

Infinite Loops and Flow Control

// infinite loop - avoid unless intentional
for (;;) { }
// control with break / continue inside the loop body

Key Points

  • for is best for a known number of iterations.
  • while checks before running; do-while checks after.
  • The enhanced for is the safest way to walk an array or collection.
Share this post:

Comments (0)

Please login or register to comment.