πŸ”
World 3 Β· Building Blocks

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 say break.
  • while β€” repeats while a condition is still true.
  • for β€” repeats over a list or a range of numbers.
Think of it like this… A loop is like a song set on repeat. It keeps playing… and playing… until you reach your limit or you hit stop (that's 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. πŸŽ‰

New word A range like 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! πŸš€

Ferris says: If you use a plain loop, don't forget a break somewhere β€” otherwise it spins forever, like a hamster wheel that never stops! 🐹
Try this! Change the range in the 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. πŸ”

You learned… Loops repeat work: 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! πŸš€