Topics: Writing Loops Part 1
These slides were last updated on July 30, 2025
Control structures let us write code that can:
Make decisions
→ with conditional statements (if
, if...else
, etc.)
Repeat actions
→ with loops (for
, while
)
Today we focus on loops, and specifically on “For loops”!
“For loops” are the most common looping construct in many programming languages. They are used to iterate over the elements of an object (usually a list or vector) and perform an action on each one.
Syntax:
for (item in sequence of items) {
action to be repeated for each item
}
Example:
Let’s break this code down:
The repeated action here is simple: print(item)
item
is a placeholder: its value changes with each loop iteration
the number of times the statement block repeats depends on the number of items in the sequence — in this example: three items, thus three times
For loops can be nested, so the outer loop controls how many times the entire inner loop runs from start to finish:
Let’s break this code down:
The outer loop runs 3 times
For each execution of the outer loop, the inner loop runs 4 times
That’s a total of 3 × 4 = 12 inner loop outputs, plus 3 outer loop prints
Observe this code. What does this code output in each run?
print(my_sum)
before my_sum <- 100 + i
print(my_sum)
add these two lines: my_sum <- 1000
and print(my_sum)
my_sum <- 1000 + my_sum
and print(my_sum)
This code defines the my_sum
variable outside the loop, before it starts. What does this code output in each run?
my_sum <- 0
to my_sum <- 100
my_sum <- 0
inside the loop, after the first two print statementsmy_sum <- 0
back outside the loop, and comment out my_sum <- my_sum + i
What we just observed is a simple example of a common task: accumulating a running total. Use it when you are adding up scores, votes, or counts one at a time, and want to keep track of how the total grows after each loop.
Same code, but with clearer print statements to make each step easier to follow:
The previous code prints the updated sum each time, but only saves the final value. To save all intermediate values, we need to store them in a vector:
Why output[i] <- my_sum
?
When i = 1
, my_sum = 0 + 1 = 1
→ store 1
in output[1]
→ output becomes: 1 0 0
When i = 2
, my_sum = 1 + 2 = 3
→ store 3
in output[2]
→ output becomes: 1 3 0
When i = 3
, my_sum = 3 + 3 = 6
→ store 6
in output[3]
→ output becomes: 1 3 6
This saves the running total at each position i
in the vector output.
Our current code works but it’s NOT yet optimal:
c(1, 2, 3)
💻 Try this:
Take the code from the previous slide and change the input vector to c(1, 4, 6)
and observe what happens to the output
. Can you explain why the result changes?
What Happens in Each Iteration
When i = 1
→ my_sum = 0 + 1 = 1
→ store 1
in output[1]
→ output becomes: 1 0 0
When i = 4
→ my_sum = 1 + 4 = 5
→ store 5
in output[4]
→ output becomes: 1 0 0 5
When i = 6
→ my_sum = 5 + 6 = 11
→ store 11 in output[6]
→ output becomes: 1 0 0 5 NA 11
R won’t throw an error if you assign to an index beyond a vector’s original length: it silently extends the vector, which can lead to unexpected results.
To fix the previous code we need to understand the difference between looping over elements and over indexes:
# Looping over values/elements
x <- c(1, 4, 6)
for (i in x) {
print(i) # value
}
# Looping over indexes (method 1)
x <- c(1, 4, 6)
for (i in 1:length(x)) {
print(i) # index
print(x[i]) # value at that index
}
# Looping over indexes (method 2)
x <- c(1, 4, 6)
for (i in seq_along(x)) {
print(i)
print(x[i])
}
i
and x[i]
Note: i
is the loop index or “counter” and should always go 1, 2, 3, 4, etc., while x[i]
is the element or value of the vector x
at position i
and can be any value
Let’s see what happens when we save the output instead of just printing:
Loop over indexes, like i in 1:length(x)
or seq_along(x)
, instead of elements/values to:
output[i] <- ...
)i
and the value at that position x[i]
You are a farmer writing a for loop to track tomatoes
sold over three days. You want to add up the number of tomatoes sold and store the running total in a vector called output
. But something is wrong with the code — can you fix it? First, think about what the output
vector should be, then check the code to see what’s going wrong.
Click on the icon bottom-right corner > Tools > PDF Export Mode > Print as a Pdf