Nested Loop
Part of the Fundamentals section of Coddy's Rust journey — lesson 41 of 75.
A nested loop is simply a loop inside another loop. The inner loop will complete all its iterations for each single iteration of the outer loop. A good analogy for this is a clock: for each hour (outer loop), the minute hand (inner loop) must complete its full 60-minute cycle.
Example of a nested loop:
for x in 0..2 {
for y in 0..2 {
println!("{} {}", x, y);
}
}
// This will output:
// 0 0
// 0 1
// 1 0
// 1 1The outer loop (x) runs twice, and for each of those times, the inner loop (y) runs twice.
Challenge
BeginnerWrite a program that finds all triplets of numbers that add up to n using numbers from 1 to n - 1. The program should show all possible combinations where the first number is less than or equal to the second number, and the second number is less than or equal to the third number (i.e., in non-decreasing order). This ensures we don't have duplicate triplets like "1 2 7" and "2 1 7" which represent the same set of numbers.
For example, if n = 10, the output should be:
1 1 8
1 2 7
1 3 6
1 4 5
2 2 6
2 3 5
2 4 4
3 3 4Because:
1 + 1 + 8 = 10
1 + 2 + 7 = 10
1 + 3 + 6 = 10
1 + 4 + 5 = 10
2 + 2 + 6 = 10
2 + 3 + 5 = 10
2 + 4 + 4 = 10
3 + 3 + 4 = 10Print order: The triplets should be printed in ascending order. The first number should iterate from smallest to largest, and for each first number, the second number should iterate from the first number to the maximum valid value, ensuring a ≤ b ≤ c.
Cheat sheet
A nested loop is a loop inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.
Basic nested loop structure:
for x in 0..2 {
for y in 0..2 {
println!("{} {}", x, y);
}
}
// Output:
// 0 0
// 0 1
// 1 0
// 1 1The outer loop runs completely, and for each iteration of the outer loop, the inner loop runs its full cycle.
Try it yourself
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();
// Write your code below
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input