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:

* * * * *
* * * * *

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
end

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

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

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

All lessons in Fundamentals