Learn
Loops
Jump Expressions

The jump expressions, break and continue, are used to change the standard loop behavior by exiting a loop early or skipping a single repetition.

The break expression is used to exit the loop at a particular iteration:

val myNumbers = listOf(4, 8, 2, 9, 12, 7, 16, 10, 3) for (num in myNumbers) { if (num > 9) { break } println(num) }

In this example:

  • the for loop iterates through the list of Ints.
  • each iteration the current number, num, is tested to see if it is greater than 9.
  • if false, the number is output.
  • if true, the break expression exits the loop.

We can see the below output stops before printing the number 12:

Output 4 8 2 9

The continue expression will skip the current execution of the loop body, but the loop will keep going if there are iterations left. If the continue expression gets executed, any code left in the current iteration will be skipped:

val myNumbers = listOf(4, 8, 2, 9, 12, 7, 16, 10, 3) for (num in myNumbers) { if (num > 9) { continue } println(num) }

This example is the same as the last but we replaced the break with continue. The below output skips all values of num greater than 9, while printing out the rest of numbers:

Output 4 8 2 9 7 3

The first example outputs the elements in myNumbers until you reach one greater than 9. The second example outputs all elements in myNumbers except those that are greater than 9.

Since jump expression are usually contained inside if expressions, they gives us the ability to add a condition to exit a for loop or using another condition to exit a while loop.

Don’t worry if this all doesn’t stick right away; keep practicing with each jump expression and you’ll quickly get the hang of how and when each one is used.

Instructions

1.

The code on the right is “looking” for something in different rooms of a house. Thankfully we know that the item being searched for is in the "Living Room".

Your job is to instruct the for loop to stop looking once it reaches "Living Room":

  • After the print("$room: ") statement add an if expression that tests if the loop variable room is equal to "Living Room".
  • Inside the if block use a println() statement to output the String, "Found It!"
  • Inside the if block add the appropriate jump expression that will stop the iteration.
2.

Good work! We also come across situations where we may want to skip a loop iteration. The second for loop in the editor causes a division by zero error. This is undesirable, and we need to add code to the body of the for loop to avoid this.

  • At the start of the loop add an if expression that tests if number is 0.
  • Inside the if expression add a continue expression.
Folder Icon

Take this course for free

Already have an account?