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 = "")
  1. values ← 2, 4, 6

    1values <- c(2, 4, 6)2total <- 0
    values this step2, 4, 6values
  2. total ← 0

    1values <- c(2, 4, 6)2total <- 03for (value in values) {
    values this step0total
  3. value ← 2

    2total <- 03for (value in values) {4  total <- total + value
    values this step2value
  4. total ← 2

    3for (value in values) {4  total <- total + value5}
    values this step0 2total2value
  5. value ← 4

    2total <- 03for (value in values) {4  total <- total + value
    values this step4value
  6. total ← 6

    3for (value in values) {4  total <- total + value5}
    values this step2 6total4value
  7. value ← 6

    2total <- 03for (value in values) {4  total <- total + value
    values this step6value
  8. total ← 12

    3for (value in values) {4  total <- total + value5}
    values this step6 12total6value
  9. cat(total, " ", sep = "")

    5}6cat(total, "\n", sep = "")
    output12
    values this step12total

Follow the Loop

  1. values starts as c(2, 4, 6).
  2. total starts at 0.
  3. The loop adds 2, then 4, then 6.
  4. After the last pass, cat prints 12. | 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.