Menu
Coddy logo textTech

Nested Loops

Part of the Fundamentals section of Coddy's R journey — lesson 44 of 78.

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 useful when working with combinations or grid-like patterns.

for (i in 1:3) {
  for (j in 1:2) {
    cat("i =", i, ", j =", j, "\n")
  }
}

Output:

i = 1 , j = 1 
i = 1 , j = 2 
i = 2 , j = 1 
i = 2 , j = 2 
i = 3 , j = 1 
i = 3 , j = 2

For each value of i, the inner loop cycles through all values of j. When i is 1, j goes from 1 to 2. Then i becomes 2, and j starts over from 1 to 2 again.

A practical example is creating a simple multiplication pattern:

for (row in 1:3) {
  for (col in 1:3) {
    cat(row * col, " ")
  }
  cat("\n")
}

Output:

1  2  3  
2  4  6  
3  6  9

The outer loop controls the rows, while the inner loop handles each column within that row. After completing each row, we print a newline to move to the next line.

challenge icon

Challenge

Easy

Read two numbers from input: rows and cols.

Use nested loops to print a rectangle of numbers where each cell contains the sum of its row number and column number. Rows are numbered from 1 to rows, and columns are numbered from 1 to cols.

Print each row on its own line, with values separated by a single space. Use cat() for output, adding a newline after each row.

For example, if the inputs are 3 and 4, the output should be:

2 3 4 5 
3 4 5 6 
4 5 6 7

In the first row (row 1), the values are 1+1=2, 1+2=3, 1+3=4, 1+4=5. In the second row (row 2), the values are 2+1=3, 2+2=4, 2+3=5, 2+4=6, and so on.

Cheat sheet

A nested loop is a loop placed inside another loop. The inner loop runs completely for each iteration of the outer loop.

for (i in 1:3) {
  for (j in 1:2) {
    cat("i =", i, ", j =", j, "\n")
  }
}

For each value of i, the inner loop cycles through all values of j.

Example creating a multiplication pattern:

for (row in 1:3) {
  for (col in 1:3) {
    cat(row * col, " ")
  }
  cat("\n")
}

The outer loop controls the rows, while the inner loop handles each column within that row. Use cat("\n") to print a newline after completing each row.

Try it yourself

# Read input
con <- file("stdin", "r")
rows <- as.integer(suppressWarnings(readLines(con, n = 1)))
cols <- as.integer(suppressWarnings(readLines(con, n = 1)))
close(con)

# TODO: Write your code below
# Use nested loops to print a rectangle where each cell contains row + column
# Use cat() to print values separated by spaces, with a newline after each row
quiz iconTest yourself

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

All lessons in Fundamentals