Chapter 13 Loops
We have already used one type of loop in our previous work, namely the
for
loop. This type of loop requires us to know up front how many times the enclosed code is to be repeated. There are situations where this is not the case however, for example if we wanted to read integers entered by the user until the user enters a certain number that signifies that they are done. This would be quite difficult to accomplish using a for
loop. In this chapter, we’ll learn about some other types of loops that are more suitable in such a situation.In order to program a loop it is often necessary to have a loop counter that needs to be updated after each run through the loop (think
i++;
for example). We’ll take a closer look at such increment and decrement operators and more generally, so-called compound assignment operators. Specifically, we’ll cover the following topics:- The
while
loop - Compound assignment operators
- Increment and decrement operators
- An in-depth look at loops (
for
andwhile
) - The
do-while
loop