Break and continue

So far you have learned how to execute a block of code repeatedly based on a particular condition using for loop, while loop, and do while loop statements. These loop statements execute a block until a certain condition is met.
Sometimes, however, you may want to have an additional control over the loop execution. The break and continue statements give you this kind control.

break statement

break statement terminates any type of loop e.g., while loop, do while loop or for loop. The break statement terminates the loop body immediately and passes control to the next statement after the loop.
The break statement is only meaningful when you put it inside a loop body, and also in the switch case statement.
We often use the break statement with the if statement, which specifies the condition to terminate the loop.
The following example illustrates how to use the break statement:
The program asked users to enter any character. If the user enters E or e, the break statement terminates the loop and control is passed to the statement after the loop that displays the Goodbye message.
Besides using the break statement to terminate a loop, we also use the  break statement to terminate the processing of a case branch in the switch case statement.

continue statement

continue statement skips the rest of the current iteration in a loop and returns to the top of the loop. The continue statement works like a shortcut to the end of the loop body.
The following example illustrates the   continue statement:
How it works.
  • First we defined an array of 10 integers from 0 to 9.
  • Second, we asked users to enter a number to find its position in the array.
  • Third, we looped over the array elements to find the input number. If the current element of the array is not equal to the input number, we displayed a message and skip the logic below it using the continue statement. If we found the element, we displayed it and exit the loop using the break statement.
The following is the output of the program when we entered number 4:
In this tutorial, we have shown you how to use the break and continue statement to control the loop iteration.

No comments:

Post a Comment