Arrays and Iteration
Array Sum (Linear Scan)
Walk an array once, accumulating each element into a running total. This is
the canonical single-pass linear scan and the simplest possible loop
invariant: after step i, total equals the sum of arr[0..i].
Algorithm
Trace Output
basic.sh
#!/usr/bin/env bash
set -euo pipefail
arr=(3 1 4 1 5 9 2 6)
total=0
i=0
while [ "$i" -lt "${#arr[@]}" ]; do
total=$((total + arr[i]))
i=$((i + 1))
done
echo "$total"
trace.sh
#!/usr/bin/env bash
set -euo pipefail
arr=(3 1 4 1 5 9 2 6)
total=0
i=0
while [ "$i" -lt "${#arr[@]}" ]; do
before=$total
total=$((total + arr[i]))
printf 'step %d: arr(%d)=%d total %d -> %d\n' "$i" "$i" "${arr[i]}" "$before" "$total"
i=$((i + 1))
done
printf 'final total = %d\n' "$total"
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Bash: use the explicit
while [ "$i" -lt "${#arr[@]}" ]loop withtotal=0and a manual 0-based index. Bash has no built-in sum primitive; piping toawk '{ s += $1 } END { print s }'would push the loop into another process the lesson is not teaching, andprintf '%s+' "${arr[@]}" 0 | bcwould defer the running update tobcand hide it. arr=(3 1 4 1 5 9 2 6)documents the fixed-content array; the manuali=$((i + 1))step keeps the iteration without leaning onfor v in "${arr[@]}"that hides the running index.set -euo pipefailat the top keeps every typo and unset variable loud, and arithmetic uses$((...))expansion so the assignments never tripset -e.- The replay shows
i,arr[i], andtotalbefore and after each addition, matching the lesson spec's state-transition table.
linear scan
Visit each element exactly once in index order.
running total
`total` accumulates the sum as the loop advances.