

Kotlin For loop
In Kotlin, The for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like C#. and foreach/for in Java. For loop in Kotlin can be used in many different ways with steps and other traverse direction likedownTo
.Kotlin For loop syntax
for (item: Int in ints) {
// ...
}
Example Kotlin For loop
fun main() {
for (i in 1..3) {
println(i)
}
}
Output
1
2
3
2
3
Example Kotlin For loop With Array
fun main() {
val fruits = arrayOf("Orange", "Apple", "Banana")
for (fruit in fruits) {
println(fruit)
}
}
Output
Orange
Apple
Banana
Apple
Banana
Example Kotlin For loop With Steps and down
In Kotlin you can loop usingstep
and downTo
fun main() {
for (i in 6 downTo 0 step 2) {
println(i)
}
}
Output
6
4
2
0
4
2
0
Conclusion
In this page (written and validated by A. Gawali) you learned about Kotlin For loop . What's Next? If you are interested in completing Kotlin tutorial, your next topic will be learning about: Kotlin Loop Break and Continue.
Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.
Share On: |
Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.