Loops in Kotlin
In this tutorial, we will learn about different types of loops in Kotlin. We will cover the basics of for, while, and do-while loops.
What is a Loop
A loop is a control flow statement that allows code to be executed repeatedly based on a condition.
Kotlin supports three types of loops: for loops, while loops, and do-while loops.
For Loop
A for loop is used when the number of iterations is known before entering the loop. The syntax for the for loop is:
for (item in collection) {
// Code block to be executed
}
While Loop
A while loop is used when the number of iterations is not known beforehand. The syntax for the while loop is:
while (condition) {
// Code block to be executed
}
Do-While Loop
A do-while loop is similar to a while loop, but it guarantees that the code block will be executed at least once. The syntax for the do-while loop is:
do {
// Code block to be executed
} while (condition)
Example 1: Printing Numbers from 1 to 10 using For Loop
- Declare an integer range from 1 to 10.
- Use a for loop to print numbers from 1 to 10.
Kotlin Program
fun main() {
for (i in 1..10) {
println(i)
}
}
Output
1 2 3 4 5 6 7 8 9 10
Example 2: Printing Numbers from 1 to 5 using While Loop
- Declare an integer variable
i
and initialize it to 1. - Use a while loop to print numbers from 1 to 5.
Kotlin Program
fun main() {
var i = 1
while (i <= 5) {
println(i)
i++
}
}
Output
1 2 3 4 5
Example 3: Printing Numbers from 1 to 3 using Do-While Loop
- Declare an integer variable
i
and initialize it to 1. - Use a do-while loop to print numbers from 1 to 3.
Kotlin Program
fun main() {
var i = 1
do {
println(i)
i++
} while (i <= 3)
}
Output
1 2 3