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
nhas positions0ton - 1.i <= nums.lengthreads one past the end and throwsArrayIndexOutOfBoundsException, which is at least an honest error. - Comparing neighbours, stop at
nums.length - 1and readnums[i]andnums[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.
whilechecks first;do whileruns once before checking.- A labelled
breakleaves several loops at once.
Next: writing your own methods.