Arrays and Iteration
Array Sum (Linear Scan)
Walk a vector 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[1..i].
Algorithm
Trace Output
basic.R
arr <- c(3, 1, 4, 1, 5, 9, 2, 6)
total <- 0
i <- 1
while (i <= length(arr)) {
total <- total + arr[i]
i <- i + 1
}
cat(total, "\n", sep = "")
trace.R
arr <- c(3, 1, 4, 1, 5, 9, 2, 6)
total <- 0
i <- 1
while (i <= length(arr)) {
before <- total
total <- total + arr[i]
cat(sprintf("step %d: arr(%d)=%d total %d -> %d\n", i, i, arr[i], before, total))
i <- i + 1
}
cat(sprintf("final total = %d\n", total))
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- R: use the explicit
while (i <= length(arr))loop withtotal <- 0and a manual 1-based index. The stdlibsum(arr)is vectorised in C and would hide the loop the lesson is teaching, andReduce("+", arr, 0)would compress the running update into a single frame. arr <- c(3, 1, 4, 1, 5, 9, 2, 6)documents the fixed-content vector; the manuali <- i + 1step keeps the iteration without leaning onfor (x in arr)that hides the running index.- R vectors are 1-indexed; the replay shows
i,arr[i], andtotalbefore and after each addition, withiranging1..8to match the actual loop counter. cat(total, "\n", sep = "")prints the final scalar without the default index marker thatprint()would emit.
linear scan
Visit each element exactly once in index order.
running total
`total` accumulates the sum as the loop advances.