A pretest loop and posttest loop produce the same results; they just use different methods.

Try the new Google Books

Check out the new look and enjoy easier access to your favorite features

A pretest loop and posttest loop produce the same results; they just use different methods.

In order to continue enjoying our site, we ask that you confirm your identity as a human. Thank you very much for your cooperation.

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

  • Repetition allows the programmer to efficiently use variables
  • Can structure programming statements to be repeated as long as specific conditions are met
  • For example: can input, add, and average multiple numbers using limited number of variables
  • There are three looping structures in C++: 1. while loop, 2. for loop, and 3. do...while Loop
  • Mnemonic: "ALL loops must have ITU"--Initialize, Test, Update

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: 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: 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:

  • Executes from zero to many times, depending on expression
  • while is reserved word
  • Syntax of while statement:
  • while (expression) statement;
  • Expression provides entry condition
  • Expression (parentheses must be included as part of syntax) must evaluate to true to invoke loop statement(s)
  • Statement(s) can be simple or compound (block)
  • Statement(s) is/are body of loop
  • BE SURE to include an exit condition that will eventually evaluate expression to be false
  • Infinite loop: statement(s) continue(s) to execute endlessly
  • Loop invocation:
    1. Statement(s) execute(s) if expression evaluates to true
    2. Loop condition reevaluated
    3. Statement(s) continue(s) to execute until expression false
Counter-Controlled while Loops:
  • When programmer knows exactly how much data should be read
  • Syntax of counter-controlled while statement:
  • int counter=0; //initialize loop control variable while (counter < n) //test loop control variable { . . . counter++; //update loop control variable . . . } Example 1: int counter=1; //initialize loop control variable while (counter < 11) //test loop control variable { cout << i << endl; //print value of i counter++; //update loop control variable } Example 2: //printing 1 - 10 using while loop cout << "while loop prints 1 - 10" << endl; int num=1; while(num < 11) { cout << num << endl; ++num; }
Sentinel-Controlled while Loops:
  • Sentinel variable tested in condition; loop ends when sentinel encountered
  • Syntax of sentinel-controlled while statement:
  • cin >> variable; //initialize loop control variable while (variable != sentinel) //test loop control variable { . . . cin >> variable; //update loop control variable . . . }
Flag-Controlled while Loops:
  • flag-controlled while loop uses bool variable to control loop
  • Syntax of flag-controlled while statement:
  • bool found = false; //initialize loop control variable while (!found) //test loop control variable { . . . if (expression) found = true; //update loop control variable . . . }
EOF (end of file)-Controlled while Loops:
  • bool value returned by cin determines if program has input
  • Syntax of EOF-controlled while statement:
  • cin >> variable; //initialize loop control variable while (cin) //test loop control variable { . . . cin >> variable; //update loop control variable . . . }
  • eof() function can determine end of file status
  • eof() function is member of data type istream--like other I/O functions (get, ignore, peek)
  • Syntax of eof() function:
  • istreamVar.eof() }
  • istreamVar is input stream variable (e.g., cin)
Code that reads integers until EOF or a non-int is encountered:
    int n; while (cin >> n) { // do whatever appropriate with n, which is ensured to be of type int } // after all ints are read, execution picks up here This works neatly, because operator >> returns zero when an error occurs, which would happen if a non-int or end-of-file is encountered.

for Loop

Using for Loop:

  • Executes a set number of times determined by the counter
  • Statement can be a single statement or a compound (block) statement.
  • for is reserved word
  • Simplifies writing of count-controlled while loop
  • Syntax of for statement (for loop control statements):
  • for (initial statement; test statement (loop condition); update statement) statement; Example: //printing 1 - 10 using for loop cout << "for loop prints 1 - 10" << endl; for(int num=1; num < 11; ++num) { cout << num << endl; }
  • for loop executes as follows:
    1. Initial statement executes (usually initializes variable)
    2. Loop condition evaluated. If loop condition evaluates to true...
      1. Execute for loop statement
      2. Execute update statement (last expression in parentheses)
      3. Repeat Step 2 until loop condition evaluates to false
  • If loop condition initially false, loop body does not execute
  • Update expression, changes value of loop control variable (initialized by initial expression), eventually sets value of loop condition to false
  • Loop body executes indefinitely if loop condition always true
  • C++ allows fractional values for loop control variables of double type (or any real data type). However, different computers may give real data type loop control variables different results--use caution with such variables
  • ***Variable used in testing for loop has local scope!
  • Can use same variable name in different for loops w/in same program--though, NOT recommended!
  • Semicolon at end of for statement (just before body of loop) is semantic error--action of for loop is empty
  • Example: for(int i = 1; i < 11; i++); //semantic error--action of for loop is empty cout << i << endl;
  • In for statement, if loop condition omitted, assumed to be true
  • In for statement, can omit all three statements: initial statement, loop condition, and update statement. "Legal," though infinite, for loop:
  • Example: for (;;) cout << "Hello" << endl;

do...while Loop

Using do...while Loop:

  • Executes at least once and up to many times depending on expression.
  • Syntax of do...while statement:
  • do statement while (expression); Example: //printing 1 - 10 using do while loop cout << "do while loop prints 1 - 10" << endl; int num1=1; do { cout << num1 << endl; num1=num1 + 1; } while(num1 < 11);
  • do...while loop executes as follows:
    1. The statement executes first, and then expression is evaluated
    2. If expression evaluates to true, statement executes again
    3. As long as expression in a do...while statement is true, statement executes
    4. Like other loops, to avoid an infinite loop, loop body must contain a statement that makes expression false
    5. Statement can be simple or compound (multiple statements); if compound, they must be in braces
    6. ***REMEMBER, posttest loops (do...while) always iterate at least once (unlike for and while)

break and continue Statements (alter flow of control)

Using break Statements:

  • When break statement executes in repetition structure, it immediately exits
  • Likewise, break statement in switch structure provides an immediate exit
  • break statement can be used in while, for, and do...while loops
  • Generally, break statement used for two purposes:
    1. To exit early from loop
    2. To skip remainder of switch structure
  • After break statement executes, program continues with first statement after structure
  • Use of break statement in loop can eliminate use of certain (flag) variables
Using continue Statements:
  • When continue statement executes in repetition structure, skips remaining statements and proceeds with next iteration of loop
  • continue statement can be used in while, for, and do...while structures
  • In while and do...while structure: expression (loop test) evaluated immediately after continue statement
  • In for structure: update statement executed after continue statement, then loop condition executes

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.