Chapter 14: Rust Loops

Rust Loops.

Loops are how we tell the computer: “Hey, repeat this block of code many times — until something tells you to stop!” Rust gives you three main loop kinds, each with its own personality:

  • loop → infinite until you break (very explicit & safe)
  • while → repeat while a condition is true
  • for → repeat over something (ranges, arrays, vectors, iterators — Rust’s favorite!)

Rust makes loops very safe — no accidental infinite loops without break, labels for nested loops, and iterators that prevent many bugs.

Let me explain like your teacher sitting next to you with a laptop: slowly, with tons of copy-paste examples (run them with cargo run), Hyderabad-flavored comments, and step-by-step from simple to advanced.

1. The loop Keyword — Infinite Until You Say Stop

loop { … } = runs forever unless you break

Rust
  • break → immediately exit the loop
  • continue → skip rest of this iteration, go to next

Classic example with continue:

Rust

Output: only odd numbers 1,3,5,7,9

2. while Loop — Repeat While Condition is True

Rust
  • Condition checked before each iteration
  • If false at start → loop body never runs

3. for Loop — Rust’s Most Loved Loop (Iterators!)

for works beautifully with ranges and collections.

A. For with Range (.. or ..=)

Rust
  • 1..6 = 1,2,3,4,5
  • 1..=5 = 1,2,3,4,5

B. For over Arrays / Slices

Rust

C. For over Vectors (growable arrays)

Rust

4. Loop Labels — For Nested Loops (Break/Continue Specific One)

Rust
  • Labels: ‘name: (apostrophe + identifier)
  • break ‘label or continue ‘label

5. Returning Values from Loops (Expression Style)

loop (and sometimes while) can return a value with break value;

Rust

Quick Summary Table (Teacher Style)

Loop Type When to Use Syntax Example Key Features
loop Infinite until explicit break loop { if cond { break; } } break, continue, labels, return value
while Repeat while condition true while x < 10 { x += 1; } Condition at top, simple counters
for Iterate over range/collection/iterator for i in 1..=10 { … } Safest & cleanest, no off-by-one bugs

Practice Tips

  1. Create cargo new rust_loops
  2. Try counting from 1 to 100 with all three kinds
  3. Make a FizzBuzz with for 1..=100
  4. Nested loop printing a small pattern (stars or Hyderabad map 😄)
  5. Use break with value to find first number divisible by 7 and 11

Rust loops feel very clean once you get used to for over iterators — most real Rust code uses for 70–80% of the time.

Next topic?

  • Functions (how loops live inside them)?
  • Ownership & borrowing with loops (very important!)?
  • Or iterators in depth (.iter(), .map(), .filter())?

Just tell me — your Rust teacher from Telangana is ready! 🦀🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *