← Back to course

Traversals, Searching & Sorting

You’ll be able to

The enhanced for-each loop

The enhanced for (for-each) loop visits every element without an index: for (int x : a) { ... } runs once per element, binding x to each value in turn. It is ideal for accumulating — summing, counting, or checking values — when you do not need the position. You cannot use it to change array elements, only to read them.

Linear search for a maximum

To find the largest value, start by assuming the first element is the max, then scan the rest and update whenever you find something bigger: int max = a[0]; then for (int i = 1; i < a.length; i++) { if (a[i] > max) { max = a[i]; } }. This linear search examines each element once and leaves max holding the greatest value.

When you need the index

Use a standard for loop with an index (for (int i = 0; i < a.length; i++)) when the algorithm needs positions — comparing neighbors, swapping elements, or writing back into the array (as sorting does). Use the for-each loop when you only read values. Choosing the right loop for the task keeps traversal code clean and correct.

Find the maximum
int max = a[0]; for (int i = 1; i < a.length; i++) if (a[i] > max) max = a[i];
Seed max with the first element, then update it whenever a larger element appears. One pass finds the maximum.
Worked example

Trace this code: int[] a = {2, 4, 6}; then int total = 0; then for (int x : a) { total += x; } then System.out.println(total);

  1. 1.Start total = 0. First element x = 2: total becomes 0 + 2 = 2.
  2. 2.Next x = 4: total becomes 2 + 4 = 6.
  3. 3.Next x = 6: total becomes 6 + 6 = 12.
  4. 4.The loop has visited every element; total is 12.
Answer: It prints 12 — the sum of 2, 4, and 6.
Checkpoint

What does this print? `int[] a = {2, 4, 6};` then `int total = 0;` then `for (int x : a) { total += x; }` then `System.out.println(total);`

Tip

Reach for the for-each loop when you just need to read every value (summing, counting, searching). Switch to an indexed for loop when you must know positions or modify the array.

Checkpoint

What does this print? `int[] a = {3, 9, 1, 7};` then `int max = a[0];` then `for (int i = 1; i < a.length; i++) { if (a[i] > max) { max = a[i]; } }` then `System.out.println(max);`

On the exam

Seed a max/min search with a[0] and start the loop at index 1. Seeding with 0 can be wrong for arrays of all-negative numbers, and forgetting to update max leaves it stuck at the first value.

Answer the 2 checkpoints as you read.

Sign in to save your progress