Chapter 9. while Running in Circles
In This Chapter
Looping using the
while
statementBreaking 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 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.