12.12.2012 Views

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

SYNTAX<br />

▼<br />

▲<br />

SYNTAX<br />

▼<br />

▲<br />

The while loop statement:<br />

while (cond_expr) {<br />

statements;<br />

}<br />

Wad<strong>in</strong>g In Deeper<br />

The while loop repeatedly executes the block of code <strong>in</strong>dicated by statements as long as the<br />

conditional expression, cond_expr, is true (nonzero). The state of the loop must be <strong>in</strong>itialized<br />

prior to the while statement, and modification of the state must be explicit <strong>in</strong> the block of<br />

code. When the conditional expression, cond_expr, evaluates to false the loop term<strong>in</strong>ates.<br />

The do-while Loop<br />

The do-while loop is nearly identical to the while loop. The dist<strong>in</strong>ction between the two is<br />

important, though. As you can see from List<strong>in</strong>g 2.2, the while loop checks the conditional<br />

expression at the top of the loop. In the case of the do-while loop, the conditional expression<br />

is checked at the bottom of the loop:<br />

bool done = false;<br />

do {<br />

// some code<br />

done = SomeFunctionReturn<strong>in</strong>gABool();<br />

// more code<br />

} while (!done)<br />

Whether you use a while or a do-while loop depends on what the loop itself does.<br />

The do-while loop statement:<br />

do {<br />

statements;<br />

} while (cond_expr)<br />

The do loop repeatedly executes the block of code <strong>in</strong>dicated by statements as long as the<br />

conditional expression, cond_expr, is true (nonzero). The state of the loop must be <strong>in</strong>itialized<br />

prior to the do statement, and modification of the state must be explicit <strong>in</strong> the block of code.<br />

When the conditional expression, cond_expr, evaluates to false, the loop term<strong>in</strong>ates.<br />

goto<br />

I’ll mention goto just so you know it exists. The goto statement allows you to jump program<br />

execution to a label that you have previously declared by us<strong>in</strong>g a term followed by a colon.<br />

The follow<strong>in</strong>g code snippet illustrates this:<br />

bool done = false;<br />

startPo<strong>in</strong>t:<br />

// do some stuff<br />

if (!done) goto(startPo<strong>in</strong>t);<br />

// loop over, mov<strong>in</strong>g on...<br />

49<br />

2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!