Menu
Coddy logo textTech

For-In Loop

Part of the Fundamentals section of Coddy's Swift journey — lesson 42 of 86.

Loops let you repeat code multiple times without writing it over and over. The for-in loop is Swift's most common loop, perfect for when you know exactly how many times you want to repeat something.

Here's the basic structure:

for number in 1...5 {
    print(number)
}
// Output: 1, 2, 3, 4, 5 (each on a new line)

The loop creates a variable called number that automatically takes each value in the range. The code inside the curly braces runs once for each value. In this case, it runs 5 times.

If you don't need the loop variable, use an underscore to ignore it:

for _ in 1...3 {
    print("Hello!")
}
// Prints "Hello!" three times

The 1...5 is a closed range that includes both 1 and 5. You can also use 1..<5 (half-open range) which includes 1 through 4, but excludes 5.

challenge icon

Challenge

Easy

Read an integer n from input. Use a for-in loop to print all numbers from 1 to n, each on a new line.

You will receive the following input:

  • A single line containing an integer as a string (e.g., "5")

Read the input, convert it to an Int, and use a for-in loop with a closed range to print each number.

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

1
2
3
4

Try it yourself

// Read input
let input = readLine()!
let n = Int(input)!

// TODO: Write your code below - use a for-in loop to print numbers 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