break and continue (Lesson-18)

The break and continue statements are used in the loops to alter the way they normally work.
Let's start with the break; statement. Whenever a break; statement is encountered inside the loop, it ends the loop. The control goes outside the loop and all the remaining statements inside the loop are skipped.
Let us consider a program to input 100 numbers from the user and display their sum on the screen but if at any point, the user inputs a zero, it will skip the remaining numbers and display the sum immediately.

Now let's talk about the continue; statement. It skips the current cycle of the loop and shifts the control to the next cycle.

Let us consider a program to display numbers from 1 to 50 but skip the multiples of three.

Practice Corner:
  • Write a program to display all the numbers from 0 to 100 but skip those which are multiples of either 5 or 7

Post a Comment