HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to KotlinVariables (val / var)Data TypesStringsListsConditions (if / when)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ String
📚 Collection
🔀 Condition & Loop
🧩 Function
Kotlin›Loops (for / while)

Loops (for / while)

For loops with ranges and lists, conditional repetition with while.

Simple enough for a 5-year-old to understand

range with for

The range written with two dots includes both the start and end values.

Example code
1
for (i in 1..5) {
From 1 to 5, including 5.
LoopFrom 1 to 5, including 5.
2
println(i)
Prints the number in each iteration.
Output / InputPrints the number in each iteration.
3
}
LoopOutput / Input
💡 Hint: If you don't want the last number to be included, use until.

Loop over a list

Example code
1
val languages = listOf("Kotlin", "Java")
2
for (lang in languages) {
Takes each element in order.
LoopTakes each element in order.
3
println(lang)
4
}
Loop

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.For which numbers does the range 1..3 iterate?

About this topic

In Kotlin, loops are written with for, while, and repeat. A for loop always iterates over something: a range, a list, or another iterable structure. The three-part counter loop from C does not exist in Kotlin.

Ranges are the foundation of loops. A range written with two dots includes the upper bound; a range written with until excludes it. When working with list indices, until is almost always the correct choice, because the last index is one less than the number of elements.

There are separate syntaxes for counting backwards and stepping: downTo moves in reverse, and step specifies the step size. These expressions are clear when read, reflecting Kotlin's overall design choice.

What you will learn

  • the for loop and ranges
  • the difference between inclusive and exclusive ranges
  • using while and do-while
  • the behavior of break and continue
  • specifying steps and reverse directions

Who is this for?

  • Learners of repetitive operations
  • Those looking for a C-style counter loop
  • Those who make mistakes with range boundaries

When to use?

A for loop is used for tasks where the number of elements is known and you are iterating over a collection.

A while loop is suitable when the number of repetitions is not known in advance; tasks that wait until a condition is met are an example of this.

Common mistakes

Wrong

val items = listOf("a", "b", "c")
for (i in 0..items.size) {
  println(items[i])
}

The two-dot range includes the upper bound, meaning the loop produces the values 0,1,2,3 and throws an IndexOutOfBoundsException on the last step. For list indices, an exclusive range should be used; even better is iterating directly over the elements instead of the indices.

Correct

val items = listOf("a", "b", "c")
for (item in items) {
  println(item)
}

Wrong

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

Since the lower bound is greater than the upper bound, the range is empty and the loop does not run at all. You won't even get an error message; the program silently does nothing, making it hard to notice. To count backwards, you need to specify a reverse direction.

Correct

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

Wrong

var i = 0
while (i < 5) {
  println(i)
}

Since the counter is not incremented, the condition remains true forever and the program never ends. You have to ensure progress yourself in while loops; this is precisely why for loops are preferred.

Correct

var i = 0
while (i < 5) {
  println(i)
  i++
}

Frequently asked questions

What is the difference between until and the two dots?

The two dots include the upper bound, while until does not. 0..4 and 0 until 5 produce the same numbers. Using until when working with indices eliminates the mistake of forgetting to subtract one from the element count.

What is the shortest way for a specific number of repetitions?

The repeat function. If you are not going to use the counter, repeat is both shorter than a for loop with a range and directly expresses the intent. If you need to, you can also access the sequence number inside the block.

How do I break the outer loop in a nested loop?

You use a label: you give the outer loop a label and direct the break command to that label. An unlabeled break only terminates the innermost loop, which is a common mistake in nested structures.

Summary

A for loop iterates over a range or collection.

Two dots include the upper bound, while until excludes it.

A reverse range remains empty; downTo must be used.

You must ensure progress in a while loop.

repeat is a shortcut for a specific number of repetitions.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code