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 />

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

immediately follow<strong>in</strong>g the loop code block. The exception to this description is the do-while<br />

loop, which tests for the condition at the bottom of the loop rather than at the top.<br />

The test condition tells the loop when to stop execut<strong>in</strong>g. In effect the test condition says, for<br />

example, “Keep do<strong>in</strong>g this until x is equal to 10,” or, “Keep read<strong>in</strong>g the file until the end-offile<br />

is reached.” Once the loop starts it cont<strong>in</strong>ues to execute the body of the loop until the test<br />

condition is met.<br />

WARNING<br />

▼<br />

▲<br />

TIP<br />

It’s easy to accidentally write a loop so that the test condition is never<br />

met. This will result <strong>in</strong> a program that is locked up or hung. Your only<br />

recourse at that po<strong>in</strong>t is to press Ctrl+Alt+Del and kill the task. The<br />

W<strong>in</strong>dows Close Program box will come up and will display the name<br />

of your program with (Not Respond<strong>in</strong>g) next to it. You’ll have to select<br />

your program from the list and click End Task to term<strong>in</strong>ate the<br />

runaway program.<br />

In <strong>C++</strong>Builder you typically run a program us<strong>in</strong>g the Run button on<br />

the Speed Bar or by press<strong>in</strong>g F9. If you need to kill a runaway program<br />

that was run from the IDE, you can choose Run | Reset Process from<br />

the ma<strong>in</strong> menu or press Ctrl+F2 on the keyboard.<br />

Given that general overview, let’s take a look at each type of loop <strong>in</strong>dividually.<br />

The for Loop<br />

The for loop is probably the most commonly used type of loop. It takes three parameters:<br />

the start<strong>in</strong>g number, the test condition that determ<strong>in</strong>es when the loop stops, and the<br />

<strong>in</strong>crement expression.<br />

The for loop statement:<br />

for (<strong>in</strong>itial; cond_expr; adjust) {<br />

statements;<br />

}<br />

The for 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 is <strong>in</strong>itialized by<br />

the statement <strong>in</strong>itial. After the execution of statements, the state is modified us<strong>in</strong>g the<br />

statement <strong>in</strong>dicated by adjust.<br />

45<br />

2

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

Saved successfully!

Ooh no, something went wrong!