There is no traditional for loop in Kotlin unlike Java and other languages.
In Kotlin, for
loop is used to iterate through ranges, arrays, maps and so on (anything that provides an iterator).
The syntax of for
loop in Kotlin is:
for (item in collection) { // body of loop }
fun main(args: Array<String>) {
for (i in 1..5) {
println(i)
}
}
Here, the loop iterates through the range and prints individual item.
When you run the program, the output will be:
1 2 3 4 5
If the body of the loop contains only one statement (like above example), it's not necessary to use curly braces { }
.
fun main(args: Array<String>) {
for (i in 1..5) println(i)
}
It's possible to iterate through a range using for
loop because ranges provides an iterator. To learn more, visit Kotlin iterators.
fun main(args: Array<String>) {
print("for (i in 1..5) print(i) = ")
for (i in 1..5) print(i)
println()
print("for (i in 5..1) print(i) = ")
for (i in 5..1) print(i) // prints nothing
println()
print("for (i in 5 downTo 1) print(i) = ")
for (i in 5 downTo 1) print(i)
println()
print("for (i in 1..4 step 2) print(i) = ")
for (i in 1..5 step 2) print(i)
println()
print("for (i in 4 downTo 1 step 2) print(i) = ")
for (i in 5 downTo 1 step 2) print(i)
}
When you run the program, the output will be:
for (i in 1..5) print(i) = 12345 for (i in 5..1) print(i) = for (i in 5 downTo 1) print(i) = 54321 for (i in 1..4 step 2) print(i) = 135 for (i in 4 downTo 1 step 2) print(i) = 531
Here's an example to iterate through a String
array.
fun main(args: Array<String>) {
var language = arrayOf("Ruby", "Koltin", "Python" "Java")
for (item in language)
println(item)
}
When you run the program, the output will be:
Ruby
Koltin
Python
Java
It's possible to iterate through an array with an index. For example,
fun main(args: Array<String>) {
var language = arrayOf("Ruby", "Koltin", "Python", "Java")
for (item in language.indices) {
// printing array elements having even index only
if (item%2 == 0)
println(language[item])
}
}
When you run the program, the output will be:
Ruby
Python
If you want to learn more about arrays, visit Kotlin arrays.
fun main(args: Array<String>) {
var text= "Kotlin"
for (letter in text) {
println(letter)
}
}
When you run the program, the output will be:
K o t l i n
Similar like arrays, you can iterate through a String
with an index. For example,
fun main(args: Array<String>) {
var text= "Kotlin"
for (item in text.indices) {
println(text[item])
}
}
When you run the program, the output will be:
K o t l i n
You will learn to iterate over a map using for
loop in Kotin map article.
It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:
Disabling AdBlock on Programiz. We do not use intrusive ads.
or
Donate on Paypal