← Back to Rust Course | Chapter 3: Control Flow | Lesson 7 of 7

Nested Loops

Sometimes you need a loop inside another loop, like checking every square on a grid one row and column at a time.

A Basic Nested Loop

Placing one for loop inside another lets you iterate over every combination of two ranges, which is the basis for processing grids, tables, and matrices.

Example: A Basic Nested Loop

markup
fn main() {
    for row in 1..=3 {
        for col in 1..=3 {
            print!("({},{}) ", row, col);
        }
        println!();
    }
}

Breaking the Inner Loop Only

By default, break only exits the innermost loop it is written in. The outer loop continues running its remaining iterations normally.

Example: Breaking the Inner Loop Only

markup
fn main() {
    for i in 1..=3 {
        for j in 1..=5 {
            if j == 2 {
                break;
            }
            println!("i={}, j={}", i, j);
        }
    }
}

Breaking the Outer Loop with a Label

To exit an outer loop from inside a nested inner loop, label the outer loop and use that label with break. This gives precise control over which loop level actually stops.

Example: Breaking the Outer Loop with a Label

markup
fn main() {
    'search: for i in 1..=3 {
        for j in 1..=3 {
            if i == 2 && j == 2 {
                println!("Found match at i={}, j={}", i, j);
                break 'search;
            }
        }
    }
    println!("Search complete");
}

Building a Multiplication Table

Nested loops are commonly used to build a full table of computed values, iterating rows on the outer loop and columns on the inner loop.

Example: Building a Multiplication Table

markup
fn main() {
    for i in 1..=3 {
        for j in 1..=3 {
            print!("{}\t", i * j);
        }
        println!();
    }
}
Common Mistakes
  1. Using unlabeled break inside a nested loop when you meant to break out of the outer loop instead of just the inner one.
  2. Writing deeply nested loops for a problem better solved with iterator combinators like .flat_map() or .zip().
  3. Forgetting that variables declared in the outer loop are reset per outer iteration if declared inside the outer loop body but outside the inner loop.
Chapter Summary
  • A loop written inside another loop's body is a nested loop, useful for grid-like or combinatorial problems.
  • Labels like 'outer: let break/continue target a specific loop level instead of just the innermost one.
  • Nested loops multiply iteration counts, so a 10x10 nested loop runs the inner body 100 times.
  • For simple transformations, iterator methods can often replace nested loops with clearer, equally fast code.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.