Loop invariants and bounded search
What you will learn
A loop invariant is a statement about the program state that remains true at a chosen point in every iteration. It helps explain why a loop gives the right answer, instead of relying on a few successful runs. Bounded search adds a clear limit to how many candidates can be inspected.
public class Main { public static void main(String[] args) { int[] deliveries = {4, 1, 7}; int total = 0; for (int units : deliveries) { total += units; System.out.println(total); } }}Expected output:
4512The successive totals represent exactly the processed prefix. The final total includes all three deliveries.
How it works
For a total, a useful invariant is: before each iteration, total equals the sum of all items already processed. Initially no items are processed, so zero is correct. Adding the next item preserves the invariant. At termination all items have been processed, so the total is complete. An array stores a fixed number of values of one type. As a short preview of the arrays chapter, int[] stock = {4, 1, 7}; creates three integers, stock.length is 3, and valid indices are 0, 1 and 2. Use for (int value : stock) to read values without needing their positions. The local value is a copy of the current int, so assigning to it does not change the array element. If a position matters, use an indexed for loop. For first-match search, keep a result of -1 until a matching index is found and stop immediately. Before each iteration, all earlier inspected positions have failed the test. The loop bound ensures finite work even when no match exists. Collections implementing Iterable also support enhanced for, covered later.
public class Main { public static void main(String[] args) { int[] stock = {8, 5, 2, 1}; int first = -1; for (int i = 0; i < stock.length; i++) { if (stock[i] < 3) { first = i; break; } } System.out.println(first); }}Expected output:
2Indices zero and one do not qualify. Index two is the first match; index three is not inspected.
Check a boundary or unusual input
public class Main { public static void main(String[] args) { int[] empty = {}; int total = 0; for (int units : empty) { total += units; } System.out.println(total); int[] stock = {4}; for (int units : stock) { units = 9; } System.out.println(stock[0]); }}Expected output:
04An empty array contributes no values. Reassigning the primitive iteration variable changes only that variable, not stock[0].
Common mistakes
For an array of length n, the last valid index is n - 1 when n is positive. Using i <= stock.length attempts an invalid index when the loop reaches length. Do not initialize a first-match result to zero because zero is a valid index. Use -1 for no match and break on the first match; without the break, the code may report the last matching position instead.
Try it yourself
Given an integer array of 0–10 elements, find the index of the first value equal to zero. Print -1 if no value matches. Test {4, 0, 0}, {}, {9, 0} and {2, 3}. Use an indexed for loop.
Save each example independently as Main.java. Compile with javac Main.java and run with java Main. Local Java practice only; automatic ByteMind Java grading is not established.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loop invariants and bounded search — knowledge check
Apply loop invariants and bounded search to examples and boundary conditions.
What is the initial running sum before any items are processed?
For an array with length 5, what is the last valid index?
Why initialize a first-match index to -1?
What does enhanced for over an empty array do?
Does reassigning an int enhanced-for variable change the original array element?