rust nested loop
To create a nested loop in Rust, you can use the for
loop within another for
loop. Here's an example:
fn main() {
for i in 1..=3 {
for j in 1..=3 {
println!("i: {}, j: {}", i, j);
}
}
}
In this example, we have two for
loops. The outer loop iterates over the values 1
to 3
(inclusive) and assigns each value to the variable i
. The inner loop also iterates over the values 1
to 3
(inclusive) and assigns each value to the variable j
. Inside the inner loop, we print the values of i
and j
.
When you run this code, it will output the following:
i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3
This demonstrates how the nested loop executes the inner loop completely for each iteration of the outer loop.
I hope this helps! Let me know if you have any further questions.