Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Break and Continue

Break and Continue


Video Summary: https://youtu.be/HUZOfbXdDsM


There are two commands you can use to skip lines in a loop:

  1. Break - immediately leaves the loop
  2. Continue - skips to the start of the next iteration of the loop

These commands can be helpful if you don't want certain lines of a loop to execute with certain input, or if you got the desired information and want to move on to a different part of your program. For example, consider the following code:


In this program, when the counter reaches three, a break statement exits the loop and goes to the end program output. For any other number, it outputs the number and restarts the loop. Since the program either exit or restarts the loop, the output on line 18 will never run.

Exercise

For this exercise, you will create a program that generates a random number between 1 and 10, then enters an infinite loop. If the player is able to guess the number, it should break from the loop and congratulate the player. Otherwise, it should prompt the user for another guess. Place an output line at the bottom of the loop that will be skipped by continue like in the example above.

When you are finished, your output might look like this:

Guess a number between 1 and 10
1
Your guess is incorrect
Guess a number between 1 and 10
2
Your guess is incorrect
Guess a number between 1 and 10
3
Your guess is correct!
		

Solution