Rs
Module 1Functions & Control FlowLesson 9 of 1024 min

loop, while, and for

Iterate scenarios, days, and Monte Carlo seeds — break, continue, and ranges.

Three loop styles

rust
fn main() {
    // infinite until break
    loop {
        break;
    }

    // condition
    let mut i = 0;
    let n = 3;
    while i < n {
        i += 1;
    }

    // iterator / range (most common)
    for day in 1..=5 {
        println!("day {day}");
    }
}
Output
day 1
day 2
day 3
day 4
day 5

Ranges

  • 0..n — exclusive end (0..3 → 0,1,2)
  • 1..=n — inclusive end
  • .rev() — reverse

break with value

rust
let found = loop {
    // ...
    break 42;
};

Example: cumulative product of returns

rust
fn wealth_path(start: f64, rets: &[f64]) -> f64 {
    let mut w = start;
    for r in rets {
        w *= 1.0 + *r;
    }
    w
}

(You’ll meet slices properly in Module 2 — here think “list of returns”.)

Exercise

Simulate 10 days of +0.1% drift and print the path.

Challenge

Nested loop: for each of 3 scenarios (rates -0.001, 0, 0.001), print a 5-day path.

Tips
  • for x in xs iterates by move/copy depending on type
  • use .iter() later when you need references
  • Prefer for over while when you know the count

Try it live

loop, while, and forRust 2021
Loading editor…
Output
Press Run to compile and execute.