Loops
Repeat work with while, range based for, and array iteration while using mutable bindings.
Core concepts
let mut, while, for, 0..n, array iteration
How the learner should approach this project
Do not paste the complete program immediately. Create the file, type the first step, run vpp check, and then run the program when a complete entry point exists. Read the explanation before looking at the snippet. After each step, predict what the new code should do. This turns the page into a lesson rather than a code dump.
Step 1: Use while and for
A binding declared with let is immutable. A counter that changes must use let mut. The while condition is checked before every iteration, so the body must eventually change i.
A range such as 0..3 produces the integer sequence used by the for loop. The array loop visits each value in the array directly, so no index is required.
After typing the snippet, identify the new names introduced by the step. Ask what each name represents, what type the compiler should infer or check, and what value should exist after the code runs.
fn main() -> int {
let mut i = 0
while i < 5 {
print(i)
i = i + 1
}
for n in 0..3 {
print(n)
}
let items = [10, 20, 30]
for val in items {
print(val)
}
return 0
}Complete source
fn main() -> int {
let mut i = 0
while i < 5 {
print(i)
i = i + 1
}
for n in 0..3 {
print(n)
}
let items = [10, 20, 30]
for val in items {
print(val)
}
return 0
}Expected behavior
The complete program should produce the following output when run with the command shown below. Exact formatting should follow the current V++ runtime.
0 1 2 3 4 0 1 2 10 20 30
Run the project
vpp run projects/04-loops/main.vppWhat the learner should understand after this project
Mutation is deliberate. A changing counter must be declared mutable, and every loop must have a clear termination condition.
Common mistakes to teach
- Using let instead of let mut for a changing counter
- Creating a while loop whose condition never becomes false
- Assuming a range loop behaves like an array index
Practice extension
Make a countdown from 5 to 1. Then make a range loop that prints only even numbers by using a conditional.
A strong learner should be able to explain the program without looking at the code, rebuild the core idea from memory, and make the practice change without copying a solution.
Full program
fn main() -> int {
let mut i = 0
while i < 5 {
print(i)
i = i + 1
}
for n in 0..3 {
print(n)
}
let items = [10, 20, 30]
for val in items {
print(val)
}
return 0
}