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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.