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.rb
arr = [3, 1, 4, 1, 5, 9, 2, 6]
total = 0
i = 0
while i < arr.length
total = total + arr[i]
i = i + 1
end
puts total
trace.rb
arr = [3, 1, 4, 1, 5, 9, 2, 6]
total = 0
i = 0
while i < arr.length
before = total
total = total + arr[i]
puts "step #{i}: arr(#{i})=#{arr[i]} total #{before} -> #{total}"
i = i + 1
end
puts "final total = #{total}"
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Ruby: use the explicit
while i < arr.lengthloop withtotal = 0and a manual index. The stdlibarr.sumis fine for production but hides the loop the lesson spec is teaching. arr = [3, 1, 4, 1, 5, 9, 2, 6]documents the fixed-content array; the manuali = i + 1step keeps the iteration without leaning oneach_with_indexorinject(:+)that hide the running update.- 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.