Menu
Coddy logo textTech

For Loop

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 46 of 93.

Sometimes you need to repeat an action multiple times. Instead of writing the same code over and over, you can use a loop. The for loop is perfect when you know exactly how many times you want to repeat something.

Here's the basic structure:

for (i in 1..5) {
    println(i)
}

This prints the numbers 1 through 5. The variable i takes each value in the range, and the code inside the curly braces runs for each value.

You can use any variable name, not just i:

for (number in 1..3) {
    println("Count: $number")
}
// Output:
// Count: 1
// Count: 2
// Count: 3

The loop variable only exists inside the loop. Each iteration, it automatically updates to the next value in the range until there are no more values left.

challenge icon

Challenge

Medium

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

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

1
2
3
4

Try it yourself

fun main() {
    val n = readLine()!!.toInt()
    
    // TODO: Write your code below to print numbers from 1 to n using a for loop
    
}
quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Kotlin playground