Loops

Repeat work with while, range based for, and array iteration while using mutable bindings.

1

Core concepts

let mut, while, for, 0..n, array iteration

2

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.

3

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.

main.vpp
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
}
4

Complete source

main.vpp
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
}
5

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
6

Run the project

terminal
vpp run projects/04-loops/main.vpp
7

What 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.

8

Common mistakes to teach

  1. Using let instead of let mut for a changing counter
  2. Creating a while loop whose condition never becomes false
  3. Assuming a range loop behaves like an array index
9

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.

10

Full program

main.vpp
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
}
vpp
$ ready. Click Test program.