Nested Loops
Part of the Fundamentals section of Coddy's Ruby journey — lesson 46 of 88.
You can place a loop inside another loop to create a nested loop. The inner loop runs completely for each iteration of the outer loop, making this pattern useful for working with grids, tables, or combinations.
for i in 1..2
for j in 1..3
puts "i=#{i}, j=#{j}"
end
endThis outputs six lines. For each value of i, the inner loop runs through all values of j.
First i is 1 while j goes 1, 2, 3. Then i becomes 2 and j again goes 1, 2, 3.
A practical example is creating a simple multiplication pattern:
for row in 1..3
for col in 1..3
print "#{row * col} "
end
puts ""
endThis prints a 3x3 grid of products. The print keeps values on the same line, and puts "" moves to a new line after each row completes. You can mix different loop types too, like a times loop inside a for loop.
Challenge
EasyRead two integers from input:
rows- the number of rowscols- the number of columns
Use nested loops to print a rectangle made of asterisks (*) with the given dimensions. Each row should contain cols asterisks separated by spaces, and each row should be on its own line.
Use print for asterisks within a row and puts to move to the next line after each row.
For example, if the inputs are 3 and 4, the output should be:
* * * *
* * * *
* * * *If the inputs are 2 and 5, the output should be:
* * * * *
* * * * *Cheat sheet
Nested loops allow you to place one loop inside another. The inner loop runs completely for each iteration of the outer loop.
for i in 1..2
for j in 1..3
puts "i=#{i}, j=#{j}"
end
endThis outputs six lines total. For i=1, j iterates through 1, 2, 3. Then for i=2, j again iterates through 1, 2, 3.
Use print to keep output on the same line and puts "" to move to a new line:
for row in 1..3
for col in 1..3
print "#{row * col} "
end
puts ""
endYou can mix different loop types, such as using a times loop inside a for loop.
Try it yourself
# Read input
rows = gets.to_i
cols = gets.to_i
# TODO: Write your code below
# Use nested loops to print a rectangle of asterisks
# Use print for asterisks within a row and puts to move to the next lineThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False