In this tutorial, we will be learning about loops in Kotlin. We will be covering different types of loops, including for loops in Kotlin. For for loops, anything that implements the Iterable interface can be utilised with the in operator. Similarly, we will learn for loops with ranges for each loop while loop in Kotlin and do-while loop.
2. Loops in Kotlin
For loop in Kotlin
For each loop in Kotlin
For loop with Ranges
While loop in Kotlin
Do- while loop in Kotlin
What’s in it for you ?
3. Loops in Kotlin
Loops are used to repeatedly execute a series of
statements until a specified/given condition is true, or the
loop is broken with the break statement, a series of
statements are run.
Loops
Do-while loops
While loop
For loop with ranges
For each loop
For loop
4. For loop in Kotlin
A for loop is a conditional iterative statement that checks
for a specific condition and then constantly executes a
block of code as long as those criteria are met.
Statements
Stop
True
Check
again
Condition
False
Initial
statement
Updation
5. For each loop in Kotlin
The forEach method in Kotlin allows you to
access elements in a collection or list and
perform actions on them.
We can achieve the same thing using the for
loop, but several for loops would quickly make
your code unreadable.
fun main(args: Array<String>)
{
var myList = listOf("Winter", "is", "Coming")
myList.forEach
{
println(it)
}
}
Output : Winter
is
Coming
6. For loop with ranges Kotlin
A range is a set of values that fall within a specified
lower and upper limit, and the values can be
numbers, characters, or objects.
Ranges might be incremental or decremental, but
the difference between two values is always 1.
fun main(args : Array<String>){
println("The range is :")
for(num in 1..8 )
{
println(num)
}
}
for( num in 1..8 step 2 )
7. While loop in Kotlin
While loops are used to repeatedly cycle a block of
code as long as the specified condition returns true.
The condition is verified first, and if it is true, the
block's code is run.
Start
Condition
Set of instructions
True
End of
loop
False
8. Do-While loop in Kotlin
The while loop and do while loop are quite the same kind of
loops.
The only difference is that in the do-while loop, the
instructions are run at least once before the condition is
evaluated.
Set of
instructions
Condition
False
End of loop
True
Do-while loop starts