Menu
Coddy logo textTech

For Loop

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

Sometimes you need to repeat an action multiple times. Instead of writing the same code over and over, you can use a for loop to execute code repeatedly.

A for loop iterates through a sequence of values, running the code inside the loop once for each value:

for (i in 1:3) {
  print(i)
}

Output:

[1] 1
[1] 2
[1] 3

The variable i takes on each value in the sequence 1:3 (which means 1, 2, 3). For each value, the code inside the curly braces { } runs once.

You can use any variable name and perform any operations inside the loop:

for (num in 1:4) {
  print(num * 2)
}

Output:

[1] 2
[1] 4
[1] 6
[1] 8

The loop multiplies each number by 2 before printing it. This is the power of loops - write the logic once, and it applies to every value in your sequence.

challenge icon

Challenge

Easy

Read a number n from input and use a for loop to print the squares of all numbers from 1 to n.

Each square should be printed on its own line using print().

For example, if the input is 4, the output should be:

[1] 1
[1] 4
[1] 9
[1] 16

Cheat sheet

A for loop executes code repeatedly by iterating through a sequence of values:

for (i in 1:3) {
  print(i)
}

The variable i takes on each value in the sequence 1:3. The code inside the curly braces { } runs once for each value.

You can use any variable name and perform operations inside the loop:

for (num in 1:4) {
  print(num * 2)
}

Output:

[1] 2
[1] 4
[1] 6
[1] 8

Try it yourself

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

# TODO: Write your code below
# Use a for loop to print the square of each number from 1 to n
quiz iconTest yourself

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

All lessons in Fundamentals