Nested Loops in Rust

Introduction to Nested Loops in Rust

Greetings! In this lesson, we're going to delve into another essential concept in Rust programming: Nested Loops. You've learned the fundamentals of looping structures in previous lessons, including the usage of for, while, and loop. Now, we're going to layer these loops to handle more complex scenarios and data manipulations.

Nested loops allow us to perform iterations within iterations. Think of it as another level of repetition where one loop runs inside another loop. This capability is vital for tasks such as multidimensional array processing, creating patterns, and more complex data manipulations.

Let's get started!

Basic Nested For Loops

Nested for loops are a powerful tool for iterating over multidimensional arrays or creating patterns. Here’s a basic example to get you started:

fn main() {
    // Start of outer loop
    for i in 1..4 {
        println!("Outer loop iteration {}", i);
        // Start of inner loop
        for j in 1..4 {
            println!("i: {}, j: {}", i, j);
        }
    }
}
/* Output
    Outer loop iteration 1
    i: 1, j: 1
    i: 1, j: 2
    i: 1, j: 3
    Outer loop iteration 2
    i: 2, j: 1
    i: 2, j: 2
    i: 2, j: 3
    Outer loop iteration 3
    i: 3, j: 1
    i: 3, j: 2
    i: 3, j: 3
*/

In this example:

  • The outer loop runs with i ranging from 1 to 3.
  • The inner loop runs with j ranging from 1 to 3 for each iteration of the outer loop.

Basic Nested While Loops

Nested while loops offer similar functionality.

fn main() {
    let mut i = 1;
    // Start of outer loop
    while i < 4 {
        println!("Outer loop iteration {}", i);
        let mut j = 1;
        // Start of inner loop
        while j < 4 {
            println!("i: {}, j: {}", i, j);
            j += 1;
        }
        i += 1;
    }
}
/* Output
    Outer loop iteration 1
    i: 1, j: 1
    i: 1, j: 2
    i: 1, j: 3
    Outer loop iteration 2
    i: 2, j: 1
    i: 2, j: 2
    i: 2, j: 3
    Outer loop iteration 3
    i: 3, j: 1
    i: 3, j: 2
    i: 3, j: 3
*/

In this example:

  • We initialized i and j outside the loops.
  • The outer while loop iterates while i is less than 4.
  • Inside the outer loop, we have another while loop iterating while j is less than 4, printing the values of i and j.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal