Nested Loops
In this page:
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
fn main() {
for row in 1..=3 {
for col in 1..=3 {
print!("({},{}) ", row, col);
}
println!();
}
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
for i in 1..=3 {
for j in 1..=5 {
if j == 2 {
break;
}
println!("i={}, j={}", i, j);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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");
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
for i in 1..=3 {
for j in 1..=3 {
print!("{}\t", i * j);
}
println!();
}
}
Login to try C/C++/Java/PHP code in the editor
- Using unlabeled
breakinside a nested loop when you meant to break out of the outer loop instead of just the inner one. - Writing deeply nested loops for a problem better solved with iterator combinators like
.flat_map()or.zip(). - 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.
- A loop written inside another loop's body is a nested loop, useful for grid-like or combinatorial problems.
- Labels like
'outer:letbreak/continuetarget 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: