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.length loop with total = 0 and a manual index. The stdlib arr.sum is 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 manual i = i + 1 step keeps the iteration without leaning on each_with_index or inject(:+) that hide the running update.
  • The replay shows i, arr[i], and total before 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.