Chapter 9. while Running in Circles

In This Chapter

  • Looping using the while statement

  • Breaking out of the middle of a loop

  • Avoiding the deadly infinite loop

  • 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 turned the wrench in a loop until the lug nut fell off, and it looped from one lug nut to the other until the entire wheel came 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 the code in the braces until expression evaluates to false (or until something else breaks the loop — more on that a little later in this chapter).

The following Factorial program demonstrates the while loop:

Note

Factorial(N) = N * (N-1) * (N-2) * ... * 1

Note

// // Factorial - calculate factorial using the while // construct. // #include <cstdio> #include <cstdlib> #include <iostream> using namespace std; int main(int ...

Get Beginning Programming with C++ For Dummies® now with O’Reilly online learning.

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