CIS 1057. Computer Programming in C

Chapter 5. Repetition and Loop Statements


1. Repetition in programs

Repetition and loop statements in C repeat compound statements until certain requirements are satisfied.

There are different types of situations when loops are involved, as shown in FIGURE 5.1:


2. The while statement

The general structure of a while statement is:
    while (condition)
where the (compound) statement is repeatedly executed while the condition remains true. The "condition" used here is as defined in the previous chapter.

The program fragment in FIGURE 5.2 contains a while statement, which repeatedly computes and displays the payments for seven employees. The process is also represented by the flowchart in Fig. 5.3:

To use a while loop, the control variable usually needs to be (1) initialized, (2) tested, and (3) updated. It is important to make sure that the loop will eventually terminate.


3. Computing a sum or product in a loop

The program in FIGURE 5.4 computes and displays the payments for any given number of employees, as well as the total amount.

C allows "compound assignment operators", which carry out operations on variables, and keep the results in the same variables. That is,

    variable op= expression;
is equivalent to
    variable = variable op (expression);
where "op" can be any arithmetic operator.


4. The for statement

The for statement in C provides a way to put all control-variable related work (initializing, testing, and updating) in the header of the loop. It is usually used for counting loops.

For example, the program fragment in FIGURE 5.5 does the payment computing using a for loop.

A for statement often uses the increment and decrement operators. For an int variable i, i++ and ++i both increase the value in i by 1; i-- and --i both decrease the value in i by 1. The value of the expressions i++ and i-- is the value before the change; the value of the expressions ++i and --i is the value after the change.

For example, the program fragment

  int n = 4;
  printf("%2d", --n);
  printf("%2d", n);
displays " 3 3"; the program fragment
  int n = 4;
  printf("%2d", n--);
  printf("%2d", n);
displays " 4 3".

For example, the program in FIGURE 5.7 computes the factorial of a given integer.

The program in FIGURE 5.8 computes and displays a table of values, where the step-size of updating is not 1.


5. Conditional loops

Conditional loops are the ones for which the number of repetitions cannot be determined in advance.

For example, if all valid observed values are non-negative, then the following loop will skip the invalid ones and warn the user:

  printf("Enter number of observed values> ");
  scanf("%d", &num_obs);
  while (num_obs < 0) {
    printf("negative number invalid; try again> ");
    scanf("%d", &num_obs);
The program will repeat the request until the user provides a valid input value. This loop is conditional because if the input is valid, the loop is skipped.

The program in FIGURE 5.9 monitors the gasoline supply in a storage tank. It contains a loop that processes the "normal" removals, until a minimum amount is reached. This loop is conditional, and in advance we don't know when it will stop.


6. Loop design

To design a loop usually means to answer the following questions:
  1. What are the inputs?
  2. What are the outputs?
  3. Is there any repetition?
  4. Do I know in advance how many times steps will be repeated?
  5. How do I know how long to keep repeating the steps?
To repeatedly process data, one way to stop the loop is to use a special data value, called "sentinel value", as a stop sign. This value cannot be a valid value to be processed by the repetition. Sentinel-controlled loops have the following format:
1. get a data item;
2. while the sentinel value has not been encountered
    3. process the item;
    4. get another data item;
Please note that line 1 is necessary for the condition of line 2 to be checked for the first item.

An example of sentinel-controlled loop is in FIGURE 5.10.

It is possible to replace the while loop (with the two statements before it) in the previous program by the following for loop (with the statement before it):

        printf("Enter the first score (%d to quit)> ", SENTINEL);
        for (scanf("%d", &score);
             score != SENTINEL;
             scanf("%d", &score)) {
          sum += score;
          printf("Enter next score (%d to quit)> ", SENTINEL);
When the input data is read from a file, a sentinel-controlled loop can be used if the number of lines to be read is unknown in advance. When scanf reaches the end of the file, it returns a standard constant EOF, which is a negative integer. For example, see FIGURE 5.11.

If the loop condition of the previous program is changed into "input_status == 1", then the loop also stops at invalid data (which will cause scanf to return 0).


7. Nested loops

A loop can contain other loops. For example, in FIGURE 5.12 there is a for loop containing a while loop. In this program, the outer loop is executed for 12 times (each per month), and the inner loop is executed until a sentinel value is encountered.

FIGURE 5.13 is a program containing a double for loops, where the inner loop is controlled by the outer loop, by using the current control-variable value of the outer loop as the bound of the control-variable of the inner loop.


8. The do-while statement and flag-controlled loops

In C, a do-while statement is just like a while statement, except that the loop condition is checked at the end of the loop body, that is: The general structure of a while statement is:
    while (condition)
For a complicated loop condition, it is often convenient to keep the loop condition in an int variable, with 1 for true (continue) and 0 for false (stop). Such a variable is called a "flag".

For example, the function in FIGURE 5.14 contains a double do-while loops, and the outer loop is controlled by a flag.


9. Iterative Approximations

In numerical analysis, the "bisection method" is widely used to interatively approaximate an solution of an equation.

Such a program needs to pass a function as a parameter, as in FIGURE 5.16. The complete program is in FIGURE 5.19.


10. How to debug programs

To debug a program, a debugger program can be used, which allow you to stop in the middle of an execution, and to check the values of variables.

To debug without a debugger, it is often helpful to insert some diagnostic calls, that is, printf statements displaying key variable values. To turn all of the diagnostic calls on or off at once, they can be put in if statements with a debug switch variable as condition.

Bugs in loops often appear at the boundary, that is, the first or last time of repetition.


11. Common programming errors

Do not confuse a while statement with an if statement.

Do not forget the two ";" in the header of a for statement.

Do not forget to put "{ }" around a loop body.

Make sure every loop will eventually terminate.

Don't mistype the "==" in a loop condition as "=".

Do not use increment, decrement, or compound assignment operators in complex expressions.