0
0
Kotlinprogramming~5 mins

Labeled break and continue in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a labeled break in Kotlin?
A labeled break in Kotlin is a way to exit a specific loop when you have nested loops. You put a label before the loop and use break with that label to stop that loop.
Click to reveal answer
beginner
How do you define a label for a loop in Kotlin?
You define a label by writing a name followed by the @ symbol before the loop. For example: outer@ for (i in 1..5) { ... }.
Click to reveal answer
intermediate
What does a labeled continue do in Kotlin?
A labeled continue skips the current iteration of the labeled loop and moves to the next iteration of that loop, even if it is an outer loop.
Click to reveal answer
intermediate
Why use labeled break or continue instead of regular break or continue?
Regular break or continue only affect the innermost loop. Labeled versions let you control outer loops directly, which is useful when you have nested loops and want to jump out or skip iterations in outer loops.
Click to reveal answer
intermediate
Example: What will this Kotlin code print?
outer@ for (i in 1..3) {
  for (j in 1..3) {
    if (i == 2 && j == 2) break@outer
    print("($i,$j) ")
  }
}
It will print: (1,1) (1,2) (1,3) (2,1) Because when i=2 and j=2, the labeled break exits the outer loop before printing (2,2).
Click to reveal answer
What does the label in Kotlin loops look like?
AA name followed by @ before the loop
BA name followed by # before the loop
CA name inside parentheses after the loop
DA name after the loop with a colon
What happens when you use break@label inside nested loops?
AIt breaks only the innermost loop
BIt causes a syntax error
CIt continues the innermost loop
DIt breaks out of the loop with the given label
Which statement is true about labeled continue in Kotlin?
AIt restarts the program
BIt breaks out of the labeled loop
CIt skips to the next iteration of the labeled loop
DIt only works with single loops
Why might you use a labeled break instead of a regular break?
ATo exit an outer loop from inside an inner loop
BTo exit only the innermost loop
CTo skip the rest of the current iteration
DTo pause the loop
What will happen if you use a label that does not exist with break or continue?
AIt breaks the innermost loop
BCompilation error
CIt continues the innermost loop
DIt ignores the label and runs normally
Explain how labeled break works in Kotlin and give a simple example.
Think about how to stop an outer loop from inside an inner loop.
You got /4 concepts.
    Describe the difference between regular continue and labeled continue in Kotlin.
    Consider what happens when you want to skip iterations in outer loops.
    You got /3 concepts.