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.ts
const arr: number[] = [3, 1, 4, 1, 5, 9, 2, 6];
let total: number = 0;
for (let i: number = 0; i < arr.length; i++) {
total = total + arr[i];
}
console.log(total);
trace.ts
const arr: number[] = [3, 1, 4, 1, 5, 9, 2, 6];
let total: number = 0;
for (let i: number = 0; i < arr.length; i++) {
const before: number = total;
total = total + arr[i];
console.log(`step ${i}: arr[${i}]=${arr[i]} total ${before} -> ${total}`);
}
console.log(`final total = ${total}`);
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- TypeScript: use the explicit
for (let i: number = 0; i < arr.length; i++)loop andlet total: number. Callingarr.reduce((a, b) => a + b, 0)would hide the iteration the lesson is teaching. - Type annotations (
: number[],: number) keep the lesson honest about the integer-array contract without changing runtime behaviour. - 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.