Mental model
A traversal visits every element of an array once, in some order, and carries a little state from one element to the next: a running total, the best value so far, whether a match has been seen. Nearly every array algorithm in the early modules is a traversal with a different piece of state, and the later patterns (two pointers, sliding windows, prefix sums) are traversals with two positions or with state that is itself an array.
The lab on this page runs the simplest traversal that can stop early: a linear search. Every step either checks the loop condition or compares one element. The searching module's linear search lesson analyses that algorithm in depth (preconditions, comparison counts, sentinels). This lesson is about the loop shapes around it.
Three ways to write the loop
for i from 0 to n - 1: # by index, forwards: you know where you are
for i from n - 1 down to 0: # by index, backwards
for each x in a: # index-free: you only need the values
| By index | Index-free | |
|---|---|---|
| C# | for (int i = 0; i < a.Length; i++) |
foreach (var x in a) |
| Python | for i in range(len(a)), better for i, x in enumerate(a) |
for x in a |
| Java | for (int i = 0; i < a.length; i++) |
for (int x : a) |
| C++ | for (std::size_t i = 0; i < a.size(); ++i) |
for (int x : a), or const auto& for large elements |
Use the index-free form when you only need values: it cannot go out of bounds and states intent. Use an
index when the position matters (the result is an index, you compare neighbours, or you write back).
Python's enumerate gives both. Backwards is reversed(a) in Python, a.rbegin()…a.rend() or
std::views::reverse in C++, and an index loop elsewhere.
A C++ trap for backwards loops: for (std::size_t i = n - 1; i >= 0; --i) never ends, because an
unsigned i is always >= 0, and when n == 0 it starts at a huge value. Write
for (std::size_t i = n; i-- > 0;) or use a signed index.
Pattern 1: accumulate
Carry one value through the loop and combine each element into it:
total = 0 # sum: start at the identity element
for each x in a: total += x
best = a[0] # maximum: start at the first element (needs n >= 1)
for i from 1 to n - 1:
if a[i] > best: best = a[i]
The starting value is the part people get wrong. A sum starts at 0 and a product at 1. A maximum has no
neutral starting value unless you pick the smallest possible one (int.MinValue,
Integer.MIN_VALUE, std::numeric_limits<int>::min(), -math.inf), which then gets returned for an
empty array as if it were data. Starting from a[0] and failing on empty input is usually more honest.
The built-ins make that choice explicit: Python's max([]) raises ValueError unless you pass
default=; C#'s Enumerable.Max throws on an empty sequence of int; Java's IntStream.max() returns
an empty OptionalInt; C++'s std::max_element returns the end iterator.
Counting (if condition: count += 1) and "does any / do all elements satisfy p" are accumulators too.
any can stop at the first true and all at the first false, which leads to the next pattern.
Pattern 2: early exit (linear search)
When the answer is decided before the end, stop:
for i from 0 to n - 1:
if a[i] == target: return i # first match: stop here
return -1 # looked at everything
That is linear search, and the lab traces it. Its cost depends on where the first match is: one comparison if it is at index 0, n if it is missing. Run the Not found preset to see the full n comparisons plus the final failing bounds check. Proving absence always costs a full traversal on unsorted data; only extra structure (sorted order, a hash set) can avoid that.
Variants of the same loop:
- Last match: traverse backwards and return the first match, or traverse forwards and remember the latest match without stopping.
- Every match: traverse without stopping and collect the indices.
- Predicate search: compare with any condition, not just equality:
Array.FindIndex,next((i for i, x in enumerate(a) if p(x)), -1),IntStream.range(0, n).filter(...).findFirst(),std::find_if.
Pattern 3: adjacent pairs and strides
To compare each element with its neighbour, the loop must stop one early:
for i from 1 to n - 1: # pairs (a[i-1], a[i]); none when n < 2
if a[i - 1] > a[i]: return "not sorted"
Starting at 1 and reading a[i − 1] keeps every access in range, including for n = 0 and n = 1, where
the loop body never runs. The alternative for i in 0 … n − 2 with a[i + 1] is equivalent but its bound
n − 2 underflows with unsigned sizes in C++. Python has itertools.pairwise(a) (3.10+) and C++23 has
std::views::adjacent<2> and std::views::pairwise.
A stride visits every k-th element: for i in range(0, n, k), for (int i = 0; i < n; i += k). It
is the shape of the jump search in the searching module and of reading one column of a matrix stored row
by row.
Pattern 4: two arrays in step
Walk two arrays with one index (zip(a, b) in Python, Enumerable.Zip in C#, std::views::zip in
C++23) or with two independent indices that advance at different times, as when merging two sorted
arrays. The second form is the two-pointer technique, which has its
own lesson.
Modifying while traversing
Changing an array's values during a loop is fine. Changing its size is where traversals break:
| Language | Adding or removing elements during foreach / iteration |
|---|---|
| C# | List<T>'s enumerator throws InvalidOperationException on the next step ("Collection was modified"). Arrays cannot change size. |
| Python | No error for lists: removing during for x in a silently skips the element after each removed one; appending can loop forever. (Dicts and sets raise RuntimeError if their size changes.) |
| Java | ArrayList's iterator throws ConcurrentModificationException on a best-effort basis; Iterator.remove() is the supported way to remove. |
| C++ | vector::erase and push_back invalidate iterators (at and after the position, or all of them on reallocation); using one afterwards is undefined behaviour. |
Safe alternatives, in order of preference: build a new array ([x for x in a if keep(x)], LINQ Where,
streams, std::copy_if); compact in place with a read index and a write index (RemoveAll, removeIf,
std::erase_if); or iterate backwards by index when deleting, so the deletions only shift elements
you have already visited.
Costs
| Pattern | Time | Extra space |
|---|---|---|
| Full traversal (sum, count, min, max) | Θ(n) | O(1) |
| Early-exit search | O(n) worst, O(1) best | O(1) |
| Adjacent pairs, strides | Θ(n), Θ(n / k) | O(1) |
| Collect every match | Θ(n) | O(m) for m matches |
| Filter into a new array | Θ(n) | O(n) |
These assume O(1) access to each element, which arrays give you. Index-based loops over a linked list would cost O(n²) in total, because reaching index i is O(i); the index-free form is O(n) on both.
The teaching implementation
The four listings below are the linear search from the searching module: an index loop, an equality
test, an early return i, and return -1 after the loop. They are the same files the lab highlights,
tested against one shared fixture and against each language's built-in search (Array.IndexOf,
list.index, List.indexOf, std::find). The other patterns in this lesson are short enough to write
from the tables above; the built-ins named there are what production code should use.
Common mistakes
i <= nin the loop condition: one access past the end.- Starting a maximum at 0: wrong for all-negative arrays. Start at
a[0]or at the type's minimum, and decide what an empty array returns. - Forgetting the early exit, or exiting on the first non-match in a search.
- Unsigned countdown loops in C++ that never terminate.
- Removing elements inside
foreach: an exception in C# and Java, skipped elements in Python, undefined behaviour in C++.
Edge cases
- Empty array: loops run zero times; sums are 0, searches return -1, minimum and maximum are undefined.
- One element: no adjacent pairs; it is both the minimum and the maximum.
- All elements equal: the first-match search returns 0; a last-match search returns n − 1.
- Duplicates of the target: decide whether you want the first, the last or all of them.
Worked practice
1. Write a loop that returns the index of the largest element (the first one if it occurs several times). What should it do for an empty array?
Answer
if n == 0: error (or return -1)
best = 0
for i from 1 to n - 1:
if a[i] > a[best]: best = i # strict >: keeps the first of equal maxima
return best
Using >= would return the last of several equal maxima.
2. How many element comparisons does a first-match linear search make on [4, 9, 4, 1] for 1, for 4, and for 7?
Answer
For 1: 4 (it is the last element). For 4: 1 (index 0). For 7: 4 (every element, then the loop ends).
3. In Python, a = [1, 2, 2, 3] and for x in a: if x == 2: a.remove(x). What is a afterwards?
Answer
[1, 2, 3]. Removing the first 2 shifts the second 2 into the current position, and the loop's internal
index moves past it. Use a = [x for x in a if x != 2].
4. Check whether an array is sorted in ascending order, without ever reading outside it, for any n ≥ 0.
Answer
for i from 1 to n - 1:
if a[i - 1] > a[i]: return false
return true
For n = 0 or 1 the loop does not run and the array is (trivially) sorted.
Summary
- Traversals visit each element once and carry a small piece of state; most array algorithms are one.
- Prefer index-free loops when positions do not matter; use an index (or
enumerate) when they do. - Accumulators need a correct starting value and a decision about empty input.
- Linear search is a traversal with an early exit; first, last, all and predicate searches are small variations. The linear search lesson covers its analysis.
- Adjacent-pair loops start at 1 and read
a[i − 1]. - Never change an array's size while iterating it; build a new one, compact in place, or go backwards.