C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

16. Breaking in and out of Looped Code


In This Chapter


  • Taking a break

  • Continuing to work


This chapter doesn’t teach you how to use another kind of loop. Instead, this chapter extends the
information you learned in the last two chapters. You have ways available to control the while loop
in addition to a relational test, and you can change the way a for loop operates via means other than
the counter variable.


The break and continue statements let you control loops for those special occasions when you
want to quit a loop early or repeat a loop sooner than it would normally repeat.


Take a break


The break statement rarely, if ever, appears on a line by itself. Typically, break appears in the
body of an if statement. The reason for this will be made clear shortly. Here is the format of
break:


break;

Note

break is easy, isn’t it? Yep, not much to it. However, keep in mind that break
usually resides in the body of an if. In a way, if is the first part of almost every
break.

break always appears inside a loop. The purpose of break is to terminate the current loop. When
a loop ends, the code following the body of the loop takes over. When break appears inside a
loop’s body, break terminates that loop immediately, and the rest of the program continues.


Here is a for loop that normally would print 10 numbers. Instead of printing 10, however, the
break causes the loop to stop after printing 5 numbers.


Click here to view code image


for (i=0; i < 10; i++)
{
printf("%d ", i)
if (i == 4)
{
break;
}
}
// Rest of program would follow.
Free download pdf