xSKILLby Infirals
Register

Java for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

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.

java
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.

java
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
java
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.

java
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.

java
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

  1. Print the numbers 1 to 10 with a for loop.
  2. Calculate the sum and the product of 1 to 5 in one loop.
  3. Count down from 5 to 1 with while, then print Lift off.
  4. Print a triangle of stars with four rows. The first row has one star and each later row has one more.
  5. Use continue to print only odd numbers from 1 to 15, then rewrite it with an if statement 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.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between a `while` loop and a `do-while` loop?

    `while` checks its condition before the first pass, so it can run zero times. `do-while` checks after the body, so it runs at least once.

  • 02What does `break` do inside a loop?

    It exits the nearest enclosing loop immediately and continues with the statement after the loop. In a `switch`, it ends the switch block.

  • 03How can a loop accidentally become infinite?

    The condition never becomes false, often because the loop variable is not updated or is updated in the wrong direction. Check that each pass moves toward the exit condition.