Doing It Again (Loops)
When a workout calls for 10 reps, you donβt write βliftβ ten separate times β you just repeat the same move until youβve hit the count. Computers are great at repeating things too, and the way they do it is called a loop! π
Three kinds of loops
Rust gives you three handy ways to repeat:
loopβ repeats forever, until you saybreak.whileβ repeats while a condition is still true.forβ repeats over a list or a range of numbers.
break). π΅
The for loop: counting made easy
The for loop is perfect when you know how many times to repeat. We use a range
like 1..=3, which means β1 up to and including 3.β
Rust ran the same line three times, once for each number in the range. The box
number held 1, then 2, then 3. π
1..=3 is a quick way to say "all the numbers
from 1 to 3." The = means "include the last one too."
The while loop: keep going until done
A while loop repeats as long as its condition stays true. Itβs great for counting
down, like a rocket launch! π
Each time around, count got one smaller. When it hit 0, the condition count > 0
became false, so the loop stopped and we blasted off! π
loop, don't forget a
break somewhere β otherwise it spins forever, like a hamster wheel that
never stops! πΉ
for loop to 1..=5 and press
βΆ Run. How many lines print now?
Quick quiz
How many lines does for n in 1..=3 print, if the body has one println!?
Yes! The range 1..=3 covers 1, 2, and 3 β so it repeats 3 times. π
loop goes forever until break,
while repeats while a condition is true, and for repeats over a
range like 1..=3. You've finished the Building Blocks world β next up, a
whole new adventure awaits! π