Repetition Structures

Why Repetition is Needed:

Repetition structures, or loops, are used when a program needs to repeatedly process one or more instructions until some condition is met, at which time the loop ends. Many programming tasks are repetitive, having little variation from one item to the next. The process of performing the same task over and over again is called iteration, and C++ provides built-in iteration functionality. A loop executes the same section of program code over and over again, as long as a loop condition of some sort is met with each iteration. This section of code can be a single statement or a block of statements (a compound statement). Loops and Using Loops


Types of Repetition Structures

Two types of repetition structures: pretest and posttest loops
Pretest:

  1. Loop condition appears at beginning of pretest loop
  2. Determines number of times instructions w/in loop body are processed
Types of pretest loop:
  1. while
  2. for
Posttest:
  1. Loop condition appears at end of posttest loop
  2. Determines number of times instructions w/in loop body are processed
  3. HOWEVER, instructions processed at least once--the first time!
Types of posttest loop:
  1. do...while while
Counter-Controlled Repetition Requires
  1. the name of a control variable (or loop counter)
  2. the initial value of the control variable
  3. the loop-continuation condition that tests for the final value of the control variable to determine when to exit
  4. the control variable to be incremented (or decremented) each time through the loop
***ALL LOOPS: if loop body contains more than one statement, statements must be entered as a statement block--that is, in a set of braces {}.

while Loop

Using while Loop:

Counter-Controlled while Loops: Sentinel-Controlled while Loops: Flag-Controlled while Loops: EOF (end of file)-Controlled while Loops: Code that reads integers until EOF or a non-int is encountered:

for Loop

Using for Loop:


do...while Loop

Using do...while Loop:


break and continue Statements (alter flow of control)

Using break Statements:

Using continue Statements:
FYI...
The continue statement cannot be used in a switch statement.

In a while loop, when the continue statement is executed, if the update statement appears after the continue statement, the update statement is not executed. In a for loop, the update statement always executes.

In general, avoid using break and continue to escape loop and branch code (one exception would be in switch statements). Instead consider adding/changing the exit conditions of the control statement. Likewise, even though permitted (due to backward-compatibility) refrain from using goto statements.

With that said, also consider how sometimes generalized rules may be reconsidered under specific circumstances.