Chapter 9

while Running in Circles

In This Chapter

arrow Looping using the while statement

arrow Breaking out of the middle of a loop

arrow Avoiding the deadly infinite loop

arrow Nesting loops within loops

Decision-making is a fundamental part of almost every program you write, which I initially emphasize in Chapter 1. However, another fundamental feature that is clear — even in the simple Lug Nut Removal algorithm — is the ability to loop. That program turns the wrench in a loop until the lug nut fallsl off, and it loops from one lug nut to the other until the entire wheel comes off. This chapter introduces you to two of the three looping constructs in C++.

Creating a while Loop

The while loop has the following format:

  while (expression){    // stuff to do in a loop}// continue here once expression is false

When a program comes upon a while loop, it first evaluates the expression in the parentheses. If this expression is true, then control passes to the first line inside the {. When control reaches the }, the program returns back to the expression and starts over. Control continues to cycle through ...

Get Beginning Programming with C++ For Dummies, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.