How to control loop in Kotlin
Welcome to kotlin Series
In this small post, we are going to discuss how to control loop in Kotlin.
Basically, we use 2 keywords for the control loop.
1. continue
2. break
if we want to skip one process, then we use to continue the keyword
But in the nested loop if we want to stop the second loop after a selected value.
But in this case, if we use break keyword in the second loop-
But our target on the basis of above value, we want to stop whole loop not only second loop after the value of a is 4.
For this case, we use loop keyword.
See the code-
sometimes we need to control the inner loop with the main loop condition. So loop keyword is saved a lot of time, we don't need to implement the complex logic.
Thank you for reading this post.
Happy coding
In this small post, we are going to discuss how to control loop in Kotlin.
Basically, we use 2 keywords for the control loop.
1. continue
2. break
if we want to skip one process, then we use to continue the keyword
for (a in 1..5){ if (a==4){ continue } println("A: $a") }Output:
A: 1 A: 2 A: 3 A: 5or if we stop the loop then we use break keyword
for (a in 1..5){ if (a==4){ break } println("A: $a") }Output:
A: 1 A: 2 A: 3
But in the nested loop if we want to stop the second loop after a selected value.
But in this case, if we use break keyword in the second loop-
for (a in 1..5){ println("A: $a") for (b in 1..5){ if (a == 4){ break } println("B: $b") } }and output:
A: 1 B: 1 B: 2 B: 3 B: 4 B: 5 A: 2 B: 1 B: 2 B: 3 B: 4 B: 5 A: 3 B: 1 B: 2 B: 3 B: 4 B: 5 A: 4 A: 5 B: 1 B: 2 B: 3 B: 4 B: 5so we see loop is not stopped. It only stops inner loop after reaching the value of a is 4. no value of this loop is not printed and it repeated every time with increasing value with a
But our target on the basis of above value, we want to stop whole loop not only second loop after the value of a is 4.
For this case, we use loop keyword.
See the code-
loop@ for (a in 1..5){ println("value a:$a") for (b in 1..4){ if (a == 4){ break@loop } println(" b:$b") } } println("Loop done")Output:
value a:1 b:1 b:2 b:3 b:4 value a:2 b:1 b:2 b:3 b:4 value a:3 b:1 b:2 b:3 b:4 value a:4 Loop doneOh! now our loop is stopped when the value of a is 4
sometimes we need to control the inner loop with the main loop condition. So loop keyword is saved a lot of time, we don't need to implement the complex logic.
Thank you for reading this post.
Happy coding
No comments :