CIS 150 Repetition

Objectives

  • use repetition in C++ programs
  • use a C++ while loop
  • use a C++ do/while loop
  • use a C++ for loop
  • use a loop counter to control a loop
  • use a sentinel value or flag to control a loop
  • discuss the differences between loop counters and sentinel values
  • use a priming read
  • discuss differences between pre-test and post-test loops
  • use accumulators with loops to calculate sums and products
  • discuss the use of break and continue

Repetition (loops)

  • Loops are one of the three main flow control structures used in structured programming. The other two are sequence and selection. Loops are also called repetition or iteration. The repetition structure allows one statement or a block of statements to be repeated. One point to remember is just because a statement is repeated doesn't mean the values of the variables in those statements are static. Usually the values of at least one variable in the loop changes with each repetition of the loop. This allows us to create accumulators (totals), allow users to repeat input as many times as needed, and manipulate multiple values stored with one variable name (arrays).
  • The relational and logical operators are used the same way they are used in selection tests.
  • The repetition structures look very similar to decision structures. A selection structure does its test once. A repetition structure keeps checking its test and executing its code until the test evaluates to false.
  • There are three repetition structures: for, while, and do/while
  • The test part of a statement should not be followed by a semicolon or the statement will end there. Example of a mistake: while (!done);
  • When you want more than one statement to be included in the body of a loop you must use curly braces to create a code block. while(test) { // statements executed within loop }
  • Remember, in a loop the code between the opening { and the closing } is repeated, run from top to bottom, as long as the condition (test) is true!
  • Loops may be either counter controlled or sentinel controlled.
  • Counter controlled loops use a variable to count (the control variable). To use a counter controlled loop you must:
    1. initialize the counter (give a starting value to the variable).
    2. test the counter to see if you should continue looping.
    3. update the counter by adding or subtracting values from it.
  • Sentinel controlled loops use a variable also. Instead of counting however, you check the variable for the sentinel (stop) value. When the test encounters the sentinel value it should be set to false so that the loop will stop. Reading in from a file or getting input from the user to determine whether or not to continue looping are examples of sentinel loops.
  • Your code can contain any combination of sequential statements, mixed with decision structure and loop structures. Nesting these structures gives you great flexibility in writing your code but also means you must be careful when designing your logic.

Pre-test loops

  • The for and while loops are top test loops. The body of the loop (block or statement) may never run if the condition is false when tested for the first time.
  • Syntax for while loop: // control variable initialized while (control_variable_test) { // statements to execute each loop iteration // control variable modified }
  • Syntax for for loop: for (control_variable_init; control_variable_test; control_variable_modification) { // statements to execute each loop iteration }
  • Example to output the numbers 1 through 7: int n = 1; while (n <= 7) { cout << n << endl; n = n + 1; }
  • Example to output the numbers 1 through 7: for (int n = 1; n <= 7; n = n + 1) { cout << n << endl; }

Post-test loop

  • The do/while loop is a bottom test loop. The body of the loop (block or statement) will always run once no matter what the test evaluates to since the test comes at the end of the loop.
  • Syntax for do/while loop: // control variable initialized do { // statements to execute each loop iteration // control variable modified } while (control_variable_test)
  • Example to output the numbers 1 through 7: int n = 1; do { cout << n << endl; n = n + 1; } while (n <= 7);

Additional repetition notes

  • Incrementing (adding 1 to) a variable is so common that there is a shorthand for it: variableName++
  • Another shorthand for incrementing a variable is: ++variableName
  • Decrementing (subtracting 1 from) a variable is so common that there is a shorthand for it: variableName--
  • Another shorthand for decrementing a variable is: --variableName
  • The modification of the loop control variable should almost always be the last statement in the loop body.
  • If a pre-test loop body consists of just one statement, the curly braces may be omitted. That statement should the be placed immediately following the test. A semicolon would then be required at the end of the statement.

Sentinel values, accumulators

A sentinel value is a special value in the input that signals special processing or the end of input. Keep in mind that the sentinel value can not then be input as one of the regular data values.

An accumulator is a variable used to sum up values. Remember to initialize accumulators to 0 before using them.

To use an accumulator for a product (multiplication), initialize it to 1 instead of 0.

int sum = 0; int num = 0; while (num != -99999) { // -99999 is the sentinel value cout << "Enter a number to be summed up: "; cin >> num if (num != -99999) { sum = sum + num; } } cout << "The sum is " << sum << endl;

Priming read

A priming read is an input of the control variable value before the loop starts to see if the loop code should be executed at all. A similar read/input is then done again at the end of the loop body.

int sum = 0; int num = 0; cout << "Enter a number to be summed up: "; cin >> num while (num != -99999) { // -99999 is the sentinel value sum = sum + num; cout << "Enter another number to be summed up: "; cin >> num } cout << "The sum is " << sum << endl;

Input validation

Loops are frequently used to validate input from users and prevent program crashes. When a number falls outside the acceptable range for use in the program use a loop that will force the user to enter an acceptable value to get out of the loop. This means that your loop test is the reverse of the stated requirement.

cout << "Enter a number between 1 and 17: "; cin >> num; while (num < 1 || num > 17) { cout << "Error: Input out of bounds" << endl; cout << "Enter a number between 1 and 17: "; cin >> num; }

Miscellaneous

  • Use the keyword break to exit a loop prematurely.
  • Use the keyword continue to skip one repeat of the loop. Be careful when using continue that you do not skip the statement that changes the value of the control variable!
  • The most important hint to write effective loops structures is to spend time before you write the code to consider how best to do them. After writing the loop, walk through it (desk check). Do you update the counter or get an new value? Do only the statements that should repeat repeat?

Examples