WHAT IS THE OUTPUT PRODUCED BY THE FOLLOWING

35. What is the output produced by the following? (x is of type int.)int x = 10;while (x > 0){ cout << x << endl; x = x + 3;}

THE

break

AND

continue

STATEMENTS

In previous subsections, we have described the basic flow of control for the

while

,

do-while

, and

for

loops. This is how the loops should normally be used and is the way

they are usually used. However, you can alter the flow of control in two ways, which in

rare cases can be a useful and safe technique. The two ways of altering the flow of con-

trol are to insert a

break

or

continue

statement. The

break

statement ends the loop.

The

continue

statement ends the current iteration of the loop body. The

break

state-

ment can be used with any of the C++ loop statements.

We described the

break

statement when we discussed the

switch

statement. The

break

statement consists of the keyword

break

followed by a semicolon. When exe-

cuted, the

break

statement ends the nearest enclosing

switch

or loop statement. Dis-

play 2.8 contains an example of a

break

statement that ends a loop when inappropriate

input is entered.

The

continue statement consists of the keyword continue

followed by a semicolon.

continue statement

When executed, the

continue

statement ends the current loop body iteration of the

nearest enclosing

loop

statement. Display 2.9 contains an example of a loop that con-

tains a

continue

statement.

One point that you should note when using the

continue

statement in a

for

loop is

that the

continue

statement transfers control to the update expression. So, any loop

control variable will be updated immediately after the

continue

statement is executed.

Note that a

break

statement completely ends the loop. In contrast, a

continue

statement merely ends one loop iteration; the next iteration (if any) continues the loop.

You will find it instructive to compare the details of the programs in Displays 2.8 and