</>CodexBash
Java
JavaBeginner9 min

Loops

The counting for loop, the enhanced for over arrays and lists, while and do while, break and continue including labelled break, and off-by-one errors.

A loop keeping a running totalstep 1/6
4
8
15
16
i = -x = -total = 0
total starts at 0, before the loop. The loop will visit each item once, left to right.

The counting for#

for (int i = 0; i < 5; i++) {
    System.out.print(i + " ");     // 0 1 2 3 4
}

Start at 0, continue while i < 5, add one each round: exactly the valid positions of an array of length five.

The enhanced for#

To visit every item without needing its position:

int[] nums = {4, 8, 15, 16, 23, 42};
long total = 0;
for (int x : nums) {
    total += x;
}
System.out.println(total);    // 108

for (String name : names) {
    System.out.println(name);
}

Read it as "for each x in nums". x is a copy of each value, so assigning to it does not change the array; use an indexed loop for that.

while and do while#

int n = 4071, digits = 0;
while (n > 0) {
    n /= 10;
    digits++;
}

int x;
do {
    x = in.nextInt();
} while (x <= 0);            // body runs at least once

Something inside a while must move it towards stopping.

break and continue#

for (int x : nums) {
    if (x < 0) break;            // leave the loop
    if (x % 2 == 1) continue;    // skip to the next item
    System.out.println(x);
}

To leave both of two nested loops at once, label the outer one:

outer:
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        if (grid[i][j] == target) {
            System.out.println(i + "," + j);
            break outer;
        }
    }
}

Off by one#

  • An array of length n has positions 0 to n - 1. i <= nums.length reads one past the end and throws ArrayIndexOutOfBoundsException, which is at least an honest error.
  • Comparing neighbours, stop at nums.length - 1 and read nums[i] and nums[i + 1].
  • Backwards: for (int i = nums.length - 1; i >= 0; i--).

Cost#

Two nested loops over n items take n × n steps: fine for a thousand, much too slow for a hundred thousand. Many algorithms exist to turn that second loop into something cheaper.

Key points#

  • for (int i = 0; i < n; i++) counts; for (int x : nums) visits each item.
  • The enhanced for gives copies; use an index to change elements.
  • while checks first; do while runs once before checking.
  • A labelled break leaves several loops at once.

Next: writing your own methods.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedRunning sumEasy
  2. Not startedBest day to buy and sellEasy
Create a free account to track your progress