Skip to main content
Rust Programming
CHAPTER 08 Beginner

Loops in Rust

Updated: May 18, 2026
5 min read

# CHAPTER 8

Loops in Rust

1. Chapter Introduction

If you need to print a user's profile 100 times, you shouldn't copy and paste the println! macro 100 times. You use loops. Rust provides three different types of loops to handle repetitive tasks: loop, while, and for. In this chapter, we will learn when and how to use each one, as well as how to exit loops early.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Create infinite loops using loop.
  • Create conditional loops using while.
  • Iterate over collections and ranges using for.
  • Control loop flow using break and continue.
  • Return values from a loop.

3. The loop Keyword

The loop keyword is unique to Rust. It creates an infinite loop that will run forever until you explicitly tell it to stop. This is often used for game engines or servers listening for network requests constantly.

You stop a loop using the break keyword.

rust
12345678910111213
fn main() {
    let mut counter = 0;

    loop {
        counter += 1;
        println!("Counter is at: {}", counter);

        if counter == 3 {
            println!("Breaking the loop!");
            break; // Exits the loop completely
        }
    }
}

Returning Values from a Loop! Because everything in Rust is an expression, loop can actually return a value when you break!

rust
123456
let result = loop {
    counter += 1;
    if counter == 10 {
        break counter * 2; // Returns 20 to the 'result' variable!
    }
};

4. The while Loop

A while loop runs code *as long as a condition evaluates to true*. The condition is checked at the beginning of each iteration.
rust
12345678910
fn main() {
    let mut fuel = 3;

    while fuel > 0 {
        println!("Engine running! Fuel remaining: {}", fuel);
        fuel -= 1; // Decrease fuel
    }

    println!("Out of fuel! System stopped.");
}

5. The for Loop (The Most Commonly Used)

The for loop is the safest and most common loop in Rust. It is used to execute code for each item in a collection (like an Array or Tuple) or a specific range of numbers.

A. Looping through a Range We use the .. syntax to define a range. 1..5 means 1 up to (but not including) 5.

rust
123456789101112
fn main() {
    // Prints 1, 2, 3, 4
    for number in 1..5 {
        println!("Number: {}", number);
    }
    
    // To include the final number, use ..=
    // Prints 1, 2, 3, 4, 5
    for number in 1..=5 {
        println!("Inclusive Number: {}", number);
    }
}

B. Looping through an Array Unlike while loops (which can accidentally cause "index out of bounds" panics if you calculate the array length wrong), for loops iterate safely.

rust
12345678
fn main() {
    let servers = ["Alpha", "Beta", "Gamma"];

    // The safest way to loop through items
    for server in servers.iter() {
        println!("Pinging server: {}", server);
    }
}

6. The continue Keyword

While break exits the loop entirely, continue skips the rest of the current iteration and jumps straight to the next one.
rust
123456789
fn main() {
    for i in 1..=5 {
        if i == 3 {
            println!("Skipping 3!");
            continue; // Jumps directly to i = 4
        }
        println!("Processing: {}", i);
    }
}

7. Mini Project: Multiplication Table Generator

Let's generate a multiplication table for the number 5 using a for loop.
rust
123456789
fn main() {
    let table_number = 5;
    println!("--- Multiplication Table for {} ---", table_number);

    for i in 1..=10 {
        let result = table_number * i;
        println!("{} x {} = {}", table_number, i, result);
    }
}

8. Common Mistakes

  • Infinite Loops by Accident: Creating a loop or a while loop but forgetting to update the condition variable (e.g., forgetting fuel -= 1), causing the program to freeze in an infinite loop.
  • Off-by-One Errors in Ranges: Thinking 1..10 includes 10. It only goes up to 9. You must use 1..=10 to include the 10.

9. Best Practices

  • Default to for loops: If you are iterating over an array or a known sequence of numbers, always use for. It prevents bugs and is highly optimized by the compiler. Only use loop when you truly need an infinite retry mechanism.

10. Exercises

  1. 1. Write a while loop that counts down from 10 to 1 and prints "Liftoff!".
  1. 2. Write a for loop that iterates through an array of three names and prints "Hello, [name]".

11. MCQs with Answers

Question 1

Which keyword creates an unconditional infinite loop?

Question 2

How do you exit a loop or while loop completely?

Question 3

Which keyword skips the current iteration and moves to the next one?

Q4. Can the loop keyword return a value? a) Yes, by passing a value after the break keyword b) No, loops are strictly statements Answer: a) Yes, by passing a value after the break keyword.
Question 5

When does a while loop evaluate its condition?

Question 6

What does the range 1..5 represent in a for loop?

Question 7

How do you make a range inclusive of the upper bound?

Question 8

Why is iterating over an array with a for loop considered safer than a while loop?

Question 9

Which loop is best for a game server that must run continuously until manually shut down?

Question 10

How do you safely iterate over an array named users using a for loop?

12. Interview Questions

  • Q: Explain why you can return a value from a loop expression but not a while expression. (Hint: while might never run if the condition is false immediately, so it can't guarantee returning a value).
  • Q: Contrast the use-cases for loop, while, and for.

13. Summary

Loops allow developers to automate repetitive tasks efficiently. While loop provides brute-force infinite repetition and while offers conditional looping, the for loop stands out as Rust's safest and most powerful tool for traversing data structures and numeric ranges.

14. Next Chapter Recommendation

Our code is getting quite long. To keep our programs organized, testable, and reusable, we need to break them down into smaller pieces. In Chapter 9: Functions in Rust, we will learn how to write custom functions, pass parameters, and return data.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·