← Kotlin tutorial

Kotlin

Loops

Kotlin's for loop steps through a range or collection directly: for (i in 1..5) includes both endpoints.

Example: summing an inclusive range

fun main() {
    var total = 0
    for (i in 1..5) {
        total += i
    }
    println("Total: $total")
}
Total: 15

1..5 is a range literal that includes both 1 and 5, compare Swift's very similar 1...5 in the Swift subject of this tutorial, or a plain for (int i = 1; i <= 5; i++) in Java or C#, which achieves the identical result with more ceremony.

Example
fun main() {
    var total = 0
    for (i in 1..5) {
        total += i
    }
    println("Total: $total")
}
Output
Total: 15
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account