Kotlin For Loop
Kotlin For loop is used to execute a block of code for each element in a given collection.
Syntax
The syntax of a For loop is
for (item in collection) {
// body
}
where
for
is keyword.(
is the syntax to define the start of condition.item
is the current item from the collection.in
is keyword.collection
is a sequence of items, like an array.)
is the syntax to define the end of condition.{
denotes the start of the For loop body.}
denotes the end of the For loop body.
Between curly braces, you can write the body of the For loop.
Examples
1. Print elements of a string array
In the following program, we take an array of strings in fruits
, and use For loop to iterate over the array, and print the elements.
Kotlin Program
fun main(args: Array<String>) {
val fruits = arrayOf("apple", "banana", "cherry")
for (fruit in fruits) {
println(fruit)
}
}
Output
apple
banana
cherry
2. Iterate over elements of an integer array
In the following program, we take an integer array in variable nums
, and use For loop to print the square of each integer value to output.
Kotlin Program
fun main(args: Array<String>) {
val nums = arrayOf(1, 2, 3, 4, 5)
for (num in nums) {
println(num * num)
}
}
Output
1
4
9
16
25