Looping Constructs


So far, you have seen that Managed C++ programs are statements that are executed sequentially from beginning to end, except when flow control dictates otherwise. Obviously, there are scenarios in which you would like to be able to repeat a single statement or a block of statements a certain number of times or until a certain condition occurs. Managed C++ provides three looping constructs for this: while, do-while, and for.

while Loop

The while loop is the simplest looping construct provided by Managed C++. It simply repeats a statement or a block of statements while the condition is true (some people prefer to say until the condition is false). The basic format of a while loop is as follows:

 while ( condition ) {      statements; } 

The condition is checked at the start of every iteration of the loop, including the first. Thus, if the condition evaluates at the start to false, then the statements never get executed. The while loop condition expression is exactly the same as an if statement condition.

In its simplest form, the while loop repeats a statement or a block of statements forever:

 while ( true ) {     statements; } 

I cover how to break out of this type of loop a little later.

More commonly, you will want the while loop condition to be evaluated. Here is an example of how to display all the numbers from 1 to 6 inclusive:

 Int32 i = 0; while ( i < 6) {     i++;     Console::WriteLine(i); } 

do-while Loop

There are scenarios in which you will want or need the loop to always execute at least once. You could do this in one of two ways:

  • Duplicate the statement or block of statements before the while loop.

  • Use the do-while loop.

Obviously, the do-while loop is the better of the two solutions.

Like the while loop, the do-while loop loops through a statement or a block of statements until a condition becomes false. Where the do-while differs is that it always executes the body of the loop at least once. The basic format of a do-while loop is as follows:

 do {     statements; } while ( condition ); 

As you can see, the condition is checked at the end of every iteration of the loop. Therefore, the body is guaranteed to execute at least once. The condition is just like the while statement and the if statement.

Like the while statement, the most basic form of the do-while loop loops forever, but because this format has no benefit over the while statement, it is seldom used. Here is the same example previously used for the while statement. It displays the numbers 1 to 6 inclusive.

 Int32 i = 0; do {     i++;     Console::WriteLine(i); } while ( i < 6 ); 

Caution

Do not forget the semicolon (;) after the closing bracket of the condition. If you do, the compiler will generate a few angry messages and not compile successfully.

for Loop

The for loop is the most complex construct for handling looping and can be used for almost any kind of loop. In its simplest form, the for loop, like the other two loop constructs, simply repeats a statement or a block of statements forever:

 for ( ; ; ) {     statements; } 

Normally, you will want control of how your program will loop, and that's what the for loop excels at. With the for loop, you can not only check to see if a condition is met like you do in the while loop, but you can also initialize and increment variables on which to base the condition. The basic format for a for loop is this:

 for (initialization; condition; increment) {     statements; } 

When the code starts executing a for loop (only the first time), the initialization is executed. The initialization is an expression that initializes variables that will be used in the loop. It is also possible to actually declare and initialize variables that will only exist while they are within the loop construct.

The condition is checked at every iteration through the loop, even the first. This makes it similar to the while loop. In fact, if you don't include the initialization and increment, the for loop acts in an identical fashion to the while loop. You can use almost any type of condition statement, so long as it evaluates to false or zero when you want to exit the loop.

The increment executes at the end of each iteration of the for loop and just before the condition is checked. Usually the code increments (or decrements) the variables that were initialized in the initialization, but this is not a requirement.

Let's look at a simple for loop in action. This for loop creates a counter i, which will iterate so long as it remains less than ten or, in other words, because you start iterating at zero, this for loop will repeat six times.

 for (Int32 i = 0; i < 6; i++) {     Console::WriteLine ( i ); } 

The output of this for loop is as follows:

 0 1 2 3 4 5 6 

One thing to note is that the initialization variable is accessible within the for loop, so it is possible to alter it while the loop is executing. For example, this for loop, though identical to the previous example, will only iterate three times:

 for (Int32 i = 0; i < 6; i++) {     i++;     Console::WriteLine ( i ); } 

The output of this for loop is as follows:

 1 3 5 

for loops are not restricted to integer type. It is possible to use floating-point or even more advanced constructs. Though this might not mean much to some of you, for loops are a handy way of iterating through link lists. (I know it is a little advanced at this point in the book, but I am throwing it in here to show how powerful the for loop can be.) For those of you who want to know what this does, it loops through the elements of a link list to the maximum of ten link list elements:

 for (Int32 i=0, list *cur=headptr; i<10 && cur->next != 0; i++, cur=cur->next) {      statements; } 

Skipping Loop Iterations

Even though you have set up a loop to iterate through multiple iterations of a block of code, there may be times that some of the iteration doesn't need to be executed. In Managed C++, you do this with a continue statement.

You will almost always find the continue statement in some type of condition statement. When the continue statement is executed, the program jumps immediately to the next iteration. In the case of the while and do-while loops, the condition is checked and the loop continues or exits depending on the result of the condition. If continue is used in a for loop, the increment executes first, and then the condition executes.

Here is a simple and quite contrived example that will print out all the prime numbers under 30:

 for (Int32 i = 1; i < 30; i++) {     if ( i % 2 == 0 && i / 2 > 1)         continue;     else if ( i % 3 == 0 && i / 3 > 1)         continue;     else if ( i % 5 == 0 && i / 5 > 1)         continue;     else if ( i % 7 == 0 && i / 7>1)         continue;     Console::WriteLine(i); } 

Breaking Out of a Loop

Sometimes you need to leave a loop early, maybe because there is an error condition and there is no point in continuing or, in the case of the loops that will loop indefinitely, you simply need a way to exit the loop. In Managed C++, you do this with a break statement. The break statement in a loop works the same way as the switch statement you saw earlier.

There is not much to the break statement. When it is executed, the loop is terminated and the flow of the program continues after the loop.

Though this is not really a very good example, the following sample shows how you could implement do-while type flow in a for loop. This loop breaks when it gets to 10:

 for ( Int32 i = 0; ; i++ ) {     Console::WriteLine(i);     if (i >= 10)         break; } 




Managed C++ and. NET Development
Managed C++ and .NET Development: Visual Studio .NET 2003 Edition
ISBN: 1590590333
EAN: 2147483647
Year: 2005
Pages: 169

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net