Break and continue

To exit a loop you can use the break statement at any time. This can be very useful if you want to stop running a loop because a condition has been met other than the loop end condition.

Example:

#include<stdio.h>
        int main()
        {
               int i;
               i = 0;
               while ( i < 20 )
               {
                       i++;
                       if ( i == 10)
                       break;
               }
               return 0;
        }

In the example above, the while loop will run, as long i is smaller then twenty. In the while loop there is an if statement that states that if i equals ten the while loop must stop (break).

With “continue;” it is possible to skip the rest of the commands in the current loop and start from the top again.

#include<stdio.h>
        int main()
        {
               int i;
               i = 0;
               while ( i < 20 )
               {
                       i++;
                       continue;
                       printf("Nothing to see\n");
               }
               return 0;
        }
In the example above,
The printf function is never called because of the  “continue;”.
Back