0
0
KotlinHow-ToBeginner · 3 min read

How to Use For Loop in Kotlin: Syntax and Examples

In Kotlin, use the for loop to repeat actions over ranges, arrays, or collections. The syntax is for (item in collection) { ... }, where item takes each value in the collection one by one.
📐

Syntax

The for loop in Kotlin iterates over anything that provides an iterator, such as ranges, arrays, or collections.

  • for: keyword to start the loop
  • (item in collection): defines the loop variable item and the collection to iterate
  • { ... }: block of code to run for each item
kotlin
for (item in collection) {
    // code to execute
}
💻

Example

This example shows how to use a for loop to print numbers from 1 to 5 using a range.

kotlin
fun main() {
    for (number in 1..5) {
        println(number)
    }
}
Output
1 2 3 4 5
⚠️

Common Pitfalls

One common mistake is trying to modify the loop variable inside the for loop, which is not allowed because it is read-only. Another is using incorrect range syntax or forgetting that ranges are inclusive.

Also, using for (i in 1 until 5) excludes 5, which can confuse beginners.

kotlin
fun main() {
    // Wrong: trying to change loop variable
    for (i in 1..3) {
        // i = i + 1 // Error: Val cannot be reassigned
        println(i)
    }

    // Correct: use a separate variable
    for (i in 1..3) {
        val j = i + 1
        println(j)
    }
}
Output
1 2 3 2 3 4
📊

Quick Reference

UsageDescription
for (item in collection)Iterate over each element in a collection or range
for (i in 1..5)Iterate from 1 to 5 inclusive
for (i in 1 until 5)Iterate from 1 to 4 (5 excluded)
for (c in "hello")Iterate over each character in a string

Key Takeaways

Use for (item in collection) to loop over ranges, arrays, or collections.
Ranges like 1..5 include both ends; use until to exclude the end.
Loop variables are read-only; do not try to modify them inside the loop.
You can loop over strings, arrays, lists, and any iterable in Kotlin.
Use clear variable names inside loops for better readability.