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 = 2For 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 9The 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
EasyRead 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 7In 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 rowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values