Loops
Control flow and methods11 min readLesson 2 of 4
2.1 The for loop
A loop repeats a block. The for loop puts three parts on one line: initialization, condition, and update. Initialization runs once, the condition is checked before every pass, and the update runs after the body.
for (int i = 1; i <= 5; i++) { ... } starts with i equal to 1 and continues while i is at most 5. After each pass, i++ adds one. The body therefore runs five times, with values 1 through 5.
The loop variable is local to the loop in this form. Choosing <= versus < changes the number of passes, so decide the intended final value before writing the condition.
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
}
}Output
Sum: 15
2.1.1 While loops and do-while loops
A while loop tests its condition before each pass. If the condition is false at the start, the body never runs. Inside the body, something must move the program toward a false condition, or the loop continues forever.
A do-while loop tests its condition after the body, so the body runs at least once. It is useful when a value must be read or an action must happen before there is anything to test. The while at the end needs a semicolon.
Before writing a loop, identify the starting state, the stopping condition, and the change made on each pass. A missing change creates an infinite loop, and a change in the wrong place can skip the intended values.
public class Main {
public static void main(String[] args) {
int count = 3;
while (count > 0) {
System.out.println(count);
count--;
}
System.out.println("Start");
}
}Output
3 2 1 Start
public class Main {
public static void main(String[] args) {
int count = 5;
do {
System.out.println("Runs once");
count++;
} while (count < 5);
System.out.println("Count: " + count);
}
}Output
Runs once Count: 6
2.1.2 Loops inside loops
A nested loop places one loop inside another. The inner loop finishes all its passes for each single pass of the outer loop. If the outer loop runs 3 times and the inner loop runs 3 times per outer pass, the inner body runs 9 times.
Nested loops are a direct way to draw rows and columns. The outer loop can control the row number, and the inner loop can print one row. A triangle pattern uses an inner loop that runs a different number of times depending on the outer value.
Keep nested loop counts small while testing. Two loops with 1,000 passes each produce 1,000,000 inner passes, which can make a slow section feel like a frozen program.
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
System.out.print("*");
}
System.out.println();
}
}
}Output
* ** *** ****
2.1.3 break and continue
break exits the nearest loop immediately. Execution continues with the first statement after the loop. In a switch, break has a similar role and ends the switch block.
continue skips the rest of the current pass and moves to the update or the next condition check. It does not exit the loop. In a for loop, the update still runs after continue, which is why the loop can still make progress.
Both statements can make a loop harder to read when used in several places. Keep the condition explicit where possible, and use break for a genuine early exit such as finding the first matching value.
public class Main {
public static void main(String[] args) {
for (int n = 10; n <= 20; n++) {
if (n % 2 == 0) {
continue;
}
if (n > 15) {
break;
}
System.out.println(n);
}
}
}Output
11 13 15
2.1.4 Bounds and common loop errors
An off-by-one error runs the body one time too many or one time too few. For values 1 through 5, i <= 5 is correct. For array indexes, which start at 0, the last valid index is length - 1, so i < length is the safe condition.
Changing the loop variable inside the body can skip values or create an infinite loop. Declare and update it in one place unless there is a clear reason to do otherwise. Do not use a floating-point counter and compare it with ==; accumulated rounding can miss the exact value.
When a loop does not seem to stop, print the counter and the condition on each pass. A short diagnostic run usually shows whether the counter is moving and which boundary is wrong.
2.1.5 Accumulators and counters
An accumulator collects a result across passes. Set it before the loop, update it inside, and print it after the loop. A sum starts at 0. A product starts at 1, because starting at 0 would keep the product at 0.
A counter tracks how many times something happened. Increment it only inside the condition you want to count. These two roles can sit in the same loop, but separate variables make the intent clearer.
Test a loop with a small number of passes before trying a large one. If the total for 1 through 5 is wrong, the same logic will be wrong for 1 through 500.
2.1.6 Practice
- Print the numbers 1 to 10 with a
forloop. - Calculate the sum and the product of 1 to 5 in one loop.
- Count down from 5 to 1 with
while, then printLift off. - Print a triangle of stars with four rows. The first row has one star and each later row has one more.
- Use
continueto print only odd numbers from 1 to 15, then rewrite it with anifstatement and compare the two versions.
For step 4, let the outer loop choose the row number and let the inner loop print exactly that many stars.
