Loops and Apply
For Loops
Accumulating a Total
A for loop repeats a block once for each value. Each iteration can update state.
Program
Play the script to watch value move through the loop and update total.
for_loop.R
Replay: real traced execution (multi-file project)
values <- c(2, 4, 6)
total <- 0
for (value in values) {
total <- total + value
}
cat(total, "\n", sep = "")
values ← 2, 4, 6
1values <- c(2, 4, 6)2total <- 0values this step2, 4, 6valuestotal ← 0
1values <- c(2, 4, 6)2total <- 03for (value in values) {values this step0totalvalue ← 2
2total <- 03for (value in values) {4 total <- total + valuevalues this step2valuetotal ← 2
3for (value in values) {4 total <- total + value5}values this step0 → 2total2valuevalue ← 4
2total <- 03for (value in values) {4 total <- total + valuevalues this step4valuetotal ← 6
3for (value in values) {4 total <- total + value5}values this step2 → 6total4valuevalue ← 6
2total <- 03for (value in values) {4 total <- total + valuevalues this step6valuetotal ← 12
3for (value in values) {4 total <- total + value5}values this step6 → 12total6valuecat(total, " ", sep = "")
5}6cat(total, "\n", sep = "")output12values this step12total
Follow the Loop
valuesstarts asc(2, 4, 6).totalstarts at0.- The loop adds
2, then4, then6. - After the last pass,
catprints12. | pass | value | total before | total after | | --- | --- | --- | --- | | 1 | 2 | 0 | 2 | | 2 | 4 | 2 | 6 | | 3 | 6 | 6 | 12 |
for
`for (value in values)` repeats once per element.
accumulator
`total` keeps state across iterations.
iteration
Each pass through the loop sees a new `value`.
Exercise: for_loop.R
Start with c(2, 4, 6), reproduce the total 12, then change one number and predict the new total before running it.