CSCD-255
2015-01-30

Link back to 29 January

Additional Loop Control Flow (Chapter 16)

break

In our programming, we have seen loops in which we have to jump over a block of code if the loop execution condition has gone false.

For instance, from 01-23 we have the program PrimeRealEstate.c in which the loop execution condition is a non-negative number.

   printf("Enter a negative number to exit the loop.\n");
   while (num >= 0) // Negative number to exit
   {
      printf("\nEnter your number:  ");
      scanf("%d", &num);

      if (num >= 0)
      {
         if (num < 2)
            printf("%d is less than 2.\n", num);
         else if (IsPrime(num))
            printf("%d is prime.\n", num);
         else
            printf("%d is composite.\n", num);
      }
   }
// Begin statements executed after the loop terminates.

It would be nice if we could bail out of the loop as soon as the loop execution condition has gone false, even though it means leaving the loop from the middle.

C provides exactly that capability with the break statement.  When the break statement executes, control passes to the statement following the current loop.

   printf("Enter a negative number to exit the loop.\n");
   while (num >= 0) // Negative number to exit
   {
      printf("\nEnter your number:  ");
      scanf("%d", &num);

      if (num < 0)
         break;
      if (num < 2)
         printf("%d is less than 2.\n", num);
      else if (IsPrime(num))
         printf("%d is prime.\n", num);
      else
         printf("%d is composite.\n", num);
   }
// Begin statements executed after the loop terminates.

continue

Sometimes you want to skip the rest of the body of the loop without exiting the loop itself.  This capability is in the continue statement.

While the break passes control all the way out of the loop,  continue statement passes control to the bottom of the loop, skipping passed the rest of the loop's contents.

For a  while and a do while loop, this means jumping to the execution condition.  The bottom of the  for loop, however, means execution of the increment (the third expression in the for loop) followed by the second expression, the execution condition.