Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 5 / 68

Loops (for statements)

In this lesson you will learn to repeat work with a for statement in Kotlin so you can process a range efficiently. This is for anyone searching for "Kotlin for loop how to use".

A range such as for (i in 1..5) drives the repetition. You can also iterate an array or a list directly with for, handling the elements without worrying about indexes.

The sample code prints numbered messages from 1 to 5 with the range for (i in 1..5). There is also the 1 until 5 form, which excludes the upper bound, and you pick to suit the job.

A common stumbling block for beginners is the difference between .. and until. The first includes the upper bound and the second does not, and missing that fine distinction shifts the number of repetitions.

In real-world development, the for statement is one of the most frequently used constructs, above all for processing the contents of a list one item at a time.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)