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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

48 Day 2<br />

Now that you’ve seen the for loop <strong>in</strong> action, it won’t be too difficult to apply the same<br />

concepts to the while and do-while loops. Let’s take a look at those now.<br />

The while Loop<br />

The while loop differs from the for loop <strong>in</strong> that it conta<strong>in</strong>s only a test condition that is<br />

checked at the start of each iteration. As long as the test condition is true, the loop keeps<br />

runn<strong>in</strong>g. Here’s an example:<br />

<strong>in</strong>t x;<br />

while (x < 1000) {<br />

x = DoSomeCalculation();<br />

}<br />

In this example I am call<strong>in</strong>g a function that I assume will eventually return a value greater than<br />

1,000. As long as the return value from this function is less than 1,000, the while loop<br />

cont<strong>in</strong>ues to run. When the variable x conta<strong>in</strong>s a value greater than or equal to 1,000, the test<br />

condition yields false, and program execution jumps to the first l<strong>in</strong>e follow<strong>in</strong>g the while<br />

loop’s end<strong>in</strong>g brace. A common implementation of a while loop uses a bool as a test variable.<br />

The state of the test variable can be set somewhere with<strong>in</strong> the body of the loop:<br />

bool done = false;<br />

while (!done) {<br />

// some code here<br />

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

// more code<br />

}<br />

At some po<strong>in</strong>t it is expected that the variable done will be false and the loop will term<strong>in</strong>ate.<br />

The program <strong>in</strong> List<strong>in</strong>g 2.2 illustrates the use of the while loop.<br />

List<strong>in</strong>g 2.2. WHILETST.CPP.<br />

1: #<strong>in</strong>clude <br />

2: #<strong>in</strong>clude <br />

3: #pragma hdrstop<br />

4: <strong>in</strong>t ma<strong>in</strong>(<strong>in</strong>t argv, char** argc)<br />

5: {<br />

6: cout

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

Saved successfully!

Ooh no, something went wrong!