Like other programming languages, Kotlin also provides many kinds of Looping methodology, In this article we will discuss about "For" loop. Kotlin "For" is similar to foreach loop in C# language.
Syntax:
for (item: Int in ints) {
print(item) // body
}
Note : Body can also be without block.
Example:
fun main(args: Array<String>) { val items = listOf(1, 2, 3, 4, 5) for (i in items) {
println("values of the array -"+i)
} }
Values of the array -1
Values of the array -2
Values of the array -3
Values of the array -4
Values of the array -5
Or you can also use range.
Example:
fun main(args: Array<String>) { for (i in 1..5) println("Loop -"+i) }
Loop -1
Loop -2
Loop -3
Loop -4
Loop -5
Kotlin also provides some library functions to make development work easier. Here is an example.
fun main(args: Array<String>) { val items = listOf(11, 22, 33, 44) for ((index, value) in items.withIndex()) { println("At index $index Value is $value") } }
At index 0 Value is 11
At index 1 Value is 22
At index 2 Value is 33
At index 3 Value is 44
Comments
Post a Comment