Skip to main content

Loops

Trushi Jasani
EditReport

Loops

for Loopโ€‹

The for loop is used to iterate over ranges, arrays, or collections.

Iterating over a Rangeโ€‹

fun main() {
for (i in 1..5) {
println(i)
}
// Output: 1 2 3 4 5
}

Descending Range with downToโ€‹

fun main() {
for (i in 5 downTo 1) {
println(i)
}
// Output: 5 4 3 2 1
}

Step Increment with stepโ€‹

fun main() {
for (i in 0..20 step 5) {
println(i)
}
// Output: 0 5 10 15 20
}

Exclusive Range with untilโ€‹

fun main() {
for (i in 1 until 5) {
println(i)
}
// Output: 1 2 3 4 (excludes 5)
}

Iterating over an Arrayโ€‹

fun main() {
val fruits = arrayOf("Apple", "Banana", "Cherry")

for (fruit in fruits) {
println(fruit)
}
}

Iterating with Indexโ€‹

fun main() {
val colors = arrayOf("Red", "Green", "Blue")

for ((index, color) in colors.withIndex()) {
println("$index: $color")
}
}

while Loopโ€‹

Repeats as long as the condition is true.

fun main() {
var count = 1

while (count <= 5) {
println("Count: $count")
count++
}
}

do-while Loopโ€‹

Executes the block at least once, then checks the condition.

fun main() {
var num = 1

do {
println("Number: $num")
num++
} while (num <= 5)
}

break โ€” Exit a Loopโ€‹

fun main() {
for (i in 1..10) {
if (i == 6) break
println(i)
}
// Output: 1 2 3 4 5
}

continue โ€” Skip an Iterationโ€‹

fun main() {
for (i in 1..10) {
if (i % 2 == 0) continue
println(i)
}
// Output: 1 3 5 7 9 (odd numbers only)
}

Labeled Loopsโ€‹

Labels help break or continue outer loops:

fun main() {
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) continue@outer
println("i=$i, j=$j")
}
}
}

Output:

i=1, j=1
i=2, j=1
i=3, j=1

Nested Loops โ€” Multiplication Tableโ€‹

fun main() {
for (i in 1..5) {
for (j in 1..5) {
print("${i * j}\t")
}
println()
}
}

repeat() Functionโ€‹

fun main() {
repeat(5) { index ->
println("Iteration $index")
}
}

Iterating Over a Stringโ€‹

fun main() {
val word = "Kotlin"
for (char in word) {
print("$char ")
}
// Output: K o t l i n
}

Loop Summaryโ€‹

Loop TypeWhen to Use
forKnown number of iterations or iterating a collection
whileRepeat while condition is true (check first)
do-whileExecute at least once (check after)
repeat(n)Run exactly n times with index available
breakExit loop early
continueSkip current iteration
Telemetry Integration

Completed working through this block? Sync progress to workspace.