Menu
Coddy logo textTech

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
end

This 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 ""
end

This 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 icon

Challenge

Easy

Read two integers from input:

  1. rows - the number of rows
  2. cols - 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:

* * * * *
* * * * *

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 line
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals