Conditional Loops

In the previous section we gave a contrived example, where the condition in the for loop polled for data:

for (; poll_data() ;) 
{
int i = get_data();
std::cout << i << std::endl;
}

In this example, there is no loop variable used in the condition. This is a candidate for the while conditional loop:

while (poll_data()) 
{
int i = get_data();
std::cout << i << std::endl;
}

The statement will continue to loop until the expression (poll_data in this case) has a value of false. As with for, you can exit the while loop with break, return, throw, or goto, and you can indicate that the next loop should be executed using the continue statement.

The first time the while statement is called, the condition is tested before the loop is executed; in some cases you may want the loop executed at least once, and then test the condition (most likely dependent upon the action in the loop) to see if the loop should be repeated. The way to do this is to use the do-while loop:

int i = 5; 
do
{
std::cout << i-- << std::endl;
} while (i > 0);

Note the semicolon after the while clause. This is required.

This loop will print 5 to 1 in reverse order. The reason is that the loop starts with i initialized to 5. The statement in the loop decrements the variable through a postfix operator, which means the value before the decrement is passed to the stream. At the end of the loop, the while clause tests to see if the variable is greater than zero. If this test is true, the loop is repeated. When the loop is called with i assigned to 1, the value of 1 is printed to the console and the variable decremented to zero, and the while clause will test an expression that is false and the looping will finish.

The difference between the two types of loop is that the condition is tested before the loop is executed in the while loop, and so the loop may not be executed. In a do-while loop, the condition is called after the loop, which means that, with a do-while loop, the loop statements are always called at least once.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset