Menu
Coddy logo textTech

Sequence Generation (seq, :)

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

You've been using 1:5 to create sequences in your loops. This colon operator is quick and simple, but R also provides the seq() function for more control over your sequences.

The colon operator creates a sequence of consecutive integers:

print(1:5)
print(10:6)

Output:

[1] 1 2 3 4 5
[1] 10 9 8 7 6

Notice that the sequence can go in either direction. When the first number is larger, it counts down.

The seq() function gives you more flexibility. You can specify a step size using the by argument:

print(seq(2, 10, by = 2))

Output:

[1] 2 4 6 8 10

This creates even numbers from 2 to 10.

You can also specify how many numbers you want using length.out:

print(seq(1, 10, length.out = 4))

Output:

[1] 1 4 7 10

R automatically calculates the spacing to give you exactly 4 evenly spaced numbers. Both approaches work seamlessly in loops, letting you iterate through custom sequences with ease.

challenge icon

Challenge

Easy

Read three numbers from input: start, end, and step.

Use the seq() function to generate a sequence from start to end with the given step size. Then use a for loop to iterate through this sequence and print the square of each number.

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

For example, if the inputs are 2, 10, and 2, the output should be:

[1] 4
[1] 16
[1] 36
[1] 64
[1] 100

This is because the sequence 2, 4, 6, 8, 10 is generated, and each number is squared.

Cheat sheet

The colon operator : creates sequences of consecutive integers:

1:5  # creates 1 2 3 4 5
10:6  # creates 10 9 8 7 6 (counts down)

The seq() function provides more control over sequences:

# Specify step size with 'by'
seq(2, 10, by = 2)  # creates 2 4 6 8 10

# Specify number of values with 'length.out'
seq(1, 10, length.out = 4)  # creates 1 4 7 10

Both the colon operator and seq() work in for loops:

for (i in seq(2, 10, by = 2)) {
  print(i)
}

Try it yourself

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

# TODO: Write your code below
# 1. Use seq() to generate a sequence from start to end with the given step
# 2. Use a for loop to iterate through the sequence
# 3. Print the square of each number using print()
quiz iconTest yourself

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

All lessons in Fundamentals