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 with total <- 0 and a manual 1-based index. The stdlib sum(arr) is vectorised in C and would hide the loop the lesson is teaching, and Reduce("+", 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 manual i <- i + 1 step keeps the iteration without leaning on for (x in arr) that hides the running index.
  • R vectors are 1-indexed; the replay shows i, arr[i], and total before and after each addition, with i ranging 1..8 to match the actual loop counter.
  • cat(total, "\n", sep = "") prints the final scalar without the default index marker that print() would emit.
linear scan Visit each element exactly once in index order.
running total `total` accumulates the sum as the loop advances.