1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Lesson Five - About Control Statements

By , About.com Guide

3 of 5

Break and Continue

These two words apply to all the loop types, i.e. while, for and do. Each behave differently.

Break

Break forces a loop to exit immediately. Here's an example:
int markerpos=-1;
for (index=0 ;index < 10;index++ )
{
if (values[index] ==-999 )
{
markerpos = index;
; break;
}
}
if (markerpos== 999)
printf("-1 Not located in array";
else
printf("-1 Found at index %i\n\r",markerpos) ;
That's a more complicated example. It searches the 10 element array values looking for a 999 value. The variable markerpos holds the position if a 999 is found. It is initialized to -1 and after the search this value is examined to see if a 999 was found.

Continue

This does the opposite of break; Instead of terminating the loop, it immediately loops again, skipping the rest of the code. So lets sum that integer array again, but this time we'll leave out elements with an index of 4 and 5.
int value =0;
for (index=0 ;index < 10;index++ )
{
if (index==4 || index==5)
continue;
value += numbers[index];
}
printf("Value = %i",value) ;
You probably won't use continue very often but it's useful on the odd occasion.

On the next page : Learn about the while and do while statements.

Explore C / C++ / C#
By Category
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Break and Continue

©2009 About.com, a part of The New York Times Company.

All rights reserved.