Programming in C

(Barry) #1

62 Chapter 5 Program Looping


Program 5.9 Output
Enter your number.
13579
97531

Program 5.9 Output (Rerun)
Enter your number.
0
0

As you can see from the program’s output, when 0 is keyed into the program, the pro-
gram correctly displays the digit 0.

The breakStatement


Sometimes when executing a loop, it becomes desirable to leave the loop as soon as a
certain condition occurs (for instance, you detect an error condition, or you reach the
end of your data prematurely).The breakstatement can be used for this purpose.
Execution of the breakstatement causes the program to immediately exit from the loop
it is executing, whether it’s a for,while, or doloop. Subsequent statements in the loop
are skipped, and execution of the loop is terminated. Execution continues with whatever
statement follows the loop.
If a breakis executed from within a set of nested loops, only the innermost loop in
which the breakis executed is terminated.
The format of the breakstatement is simply the keyword breakfollowed by a semi-
colon:
break;

The continueStatement


The continuestatement is similar to the breakstatement except it doesn’t cause the
loop to terminate. Rather, as its name implies, this statement causes the loop in which it
is executed to be continued. At the point that the continuestatement is executed, any
statements in the loop that appear afterthe continuestatement are automatically
skipped. Execution of the loop otherwise continues as normal.
The continuestatement is most often used to bypass a group of statements inside a
loop based upon some condition, but to otherwise continue execution of the loop.The
format of the continuestatement is simply
continue;
Don’t use the breakor continuestatements until you become very familiar with writ-
ing program loops and gracefully exiting from them.These statements are too easy to
abuse and can result in programs that are hard to follow.
Free download pdf