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:
let rows = 2;
let cols = 2;
for x in 0..rows {
for y in 0..cols {
println!("{} {}", x, y);
}
}
// This will output:
// 0 0
// 0 1
// 1 0
// 1 1The outer loop (x) runs rows times, and for each of those times, the inner loop (y) runs cols times. Each loop has its own counter: y starts again from 0 every time the outer loop runs, while rows and cols stay the same and only tell the loops when to stop.
Challenge
BeginnerWrite a program that prints a rectangle of asterisks (*) with a given width and height.
Input: Two integers: width and height (the starter code already reads them).
For example:
If width = 5 and height = 3, the output should be:
*****
*****
*****If width = 4 and height = 6, the output should be:
****
****
****
****
****
****Use a new counter for each loop (for example i for the rows and j for the stars in a row) and compare it with height or width. Don't change height and width themselves: every row needs width again.
Try it yourself
use std::io;
fn main() {
let mut width_input = String::new();
let mut height_input = String::new();
io::stdin().read_line(&mut width_input).unwrap();
io::stdin().read_line(&mut height_input).unwrap();
let width: i32 = width_input.trim().parse().unwrap();
let height: i32 = height_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 InputPractice on your own: Online Rust compiler