6.4. Finishing iterations with continue

Sometimes, you are in a loop and want to finish the current iteration and immediately jump to the next. In that case, you can use the continue statement to skip to the next iteration without finishing the body of the loop for the current iteration.

Here is an example of a loop that copies its input until the user types “done”, but treats lines that start with the hash character as lines not to be printed (kind of like Python comments).

Here is a sample run of this new program with continue added:

Try the code block above using the input below as well as your own input.

> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done!

All the lines are printed except the one that starts with the hash sign because when the continue is executed, it ends the current iteration and jumps back to the while statement to start the next iteration, thus skipping the print statement.

Construct a block of code that prints the numbers 1 through 10, but skips the number 8. The loop will start by incrementing n, before doing anything else. Look out for the three extra code pieces and watch your indentation!

You have attempted of activities on this page