Kotlin Loops
$count++; if($count == 1) { include "../mobilemenu.php"; } if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
Kotlin Loops:
Loops are used in cases where you need to repeat a set of instructions over and over again until a certain condition is met.
There are three primary types of looping in Kotlin.
For Loop - Back to top
Example:fun main(args: Array<String>) {
for( i in 1..5)
{
print(i)
}
}
Output:
12345
The second operation is checking upto when the loop is valid. In this case, the loop is valid for i range 1 to 5.
While Loop - Back to top
Example:fun main(args: Array<String>) {
var i: Int = 0
while(i < 10)
{
println(i)
i++
}
}
Output:
0
1
2
3
4
5
6
7
8
9
Here we initialized i to 0. In the while statement, we have kept until when the loop is valid.
So here we check up to i < 10. Inside the while loop we are printing i and then incrementing it by 1.
Imagine what would happen if we don't increment i by 1?
The loop will keep running a concept called infinite loop. Eventually the program will crash.
Do While Loop - Back to top
Example:fun main(args: Array<String>) {
var i: Int = 0
do{
println(i)
i++;
}while(i < 10)
}
Output:
0
1
2
3
4
5
6
7
8
9
In do while loop you are guaranteed that the loop will execute at least once.
This is because the condition i < 10 is checked at the end of the execution.
Break and Continue:
Break statement:
A break statement will stop the current loop and it will continue to the next statement of the program after the loop.
Example of Break:
fun main(args: Array<String>) {
var i: Int = 0
while(i < 10)
{
i += 1;
print(i)
if(i == 5)
{
break
}
}
}
Output:
12345
When the value of i is 5, we are breaking the loop.
Continue Statement:
Continue will stop the current iteration of the loop and it will start the next iteration.
It is very useful when we have some exception cases, but do not wish to stop the loop for such scenarios.
Example:
fun main(args: Array<String>) {
var i: Int = 0
while(i < 10)
{
i++
if(i%2 == 0)
{
continue
}
print(i)
}
}
Output:
13579
So we end up printing only odd numbers.