Repeating with loops
Run the same code many times without writing it many times.
Your Rust code runs inside your browser tab. Nothing to install.
Counting with a loop
A loop runs the same block of code several times.
for i in 1..=3 runs the block once for each number from 1 to 3. The = means the last number is included. Without it, the range stops one short.
The loop variable holds a different number on each pass.
fn main() {
for i in 1..=3 {
println!("{}", i);
}
}Your turn: counting
Count a little further than the example does.
Practice task
Use a loop to print the numbers from 1 to 5, one on each line.
Your answer is run and checked in the lesson. Create a free account to try it.
Building up a result
A loop is often used to build up one answer. Create a variable before the loop, change it inside the loop, and use it after the loop.
The total is created with let mut because the loop changes it. total += i is a short way to write total = total + i.
The print in the example comes after the loop has closed, so it runs once, at the end.
fn main() {
let mut total = 0;
for i in 1..=4 {
total += i;
}
println!("{}", total);
}Repeating while something is true
A while loop repeats for as long as its condition is true. Use it when you do not know in advance how many passes are needed.
Something inside the loop must change so that the condition becomes false. If nothing does, the loop never ends.
The example halves a number until it drops below 10.
fn main() {
let mut n = 80;
while n >= 10 {
println!("{}", n);
n = n / 2;
}
}Your turn: a total
Combine a loop with a running total.
Practice task
Use a loop to add the numbers from 1 to 10, then print the total once.
Your answer is run and checked in the lesson. Create a free account to try it.