Loops

While we used recursion to do repetition in Scheme, the primary mechanism for repetition in a C program is a new construct called a "loop". There are several varieties, which you'll learn about in the following textbook readings and examples.

Textbook reading

A Simple Counting Loop

As a basic program about loops, consider the following code that prints the numbers from one to ten, with each number on a new line. Commentary after the program explains each element of this program.

/* A simple loop that prints the numbers from 1 to 10. */
#include <stdio.h>

int
main (void)
{
  int i;

  printf ("Program to print the numbers from 1 to 10.\n");

  for (i = 1; i < 11; i++)
  {
    printf ("%d\n", i);
  }

  return 0;
} // main

A for loop is composed of an initializing statement, and a body of actions. The initializing statement has three components which are separated by semi-colons.

Loop Header

Example: for (i = 1; i < 11; i++)

Let's break down this statement into its components and explain each one in turn.

Variable Initialization

Example: i = 1

This line initializes one or more variables at the beginning of the loop. If multiple variables are initialized here, they are separated by commas. While it is not absolutely necessary to have a variable initialized here (the variable could be initialized earlier in the program), initializing the variable here means that the variable is predictable, as it has not been changed between being initialized and used in the loop.

Note that while you can also declare the variable in this component (example: int i = 1), professional programmers disagree whether this is acceptable.

Continuation Expression(s)

Example: i < 11

This line determines whether the loop should continue. As long as the expression evaluates to true, the loop continues for another iteration. As with any logical expression, the continuation expression may include multiple subexpressions here, connected with && (all subexpressions must be true) or || (at least one subexpression must be true).

Warning: if the continue condition is not specified, the loop will not stop. Be careful!

Loop Action

Example: i++

This line determines the action taken at the end of each iteration of the loop. In this program, after each time the program goes through the loop, the variable i is increased by one, then the continue condition is tested. If what is tested by the continue condition never changes, the loop will not finish.

Loop Body

The C programming language treats the for loop body as a single unit. Either the body is composed of a single line, or the body of the for loop contains multiple commands enclosed by curly braces, which are also treated as a single unit.

Nested Loops

As a basic program about nested loops, consider the following code that prints rows with increasing numbers of asterisks. Commentary after the program explains each element of this program.

#include <stdio.h>

int
main (void)
{
  int i, j;
  
  printf ("Program to print rows with increasing numbers of asterisks.\n");

  for (i = 1; i < 11; i++)
  {
    for (j = 0; j < i; j++)
    {
      printf ("*");
    } // for j
    printf ("\n");
  } // for i

  return 0;
} // main

Programming Hint—Infinite Loops:

Computers are quite patient, so once a loop starts, the loop will continue as long as the appropriate condition remains true. If the condition never becomes false, the loop will never stop. For example, the following loop will continue forever (assuming your program has the line #include <stdbool.h>)


while (true)
{

}

Although this type of construct may seem peculiar, such loops can be useful from time to time. For example, we expect to type commands in a terminal window for as long as the window remains open. Thus, the code behind the terminal window might use a while (true) construct to keep reading and processing commands.

As a practical matter, if you encounter this situation with a program, and if you want the program to stop, you can use the key combination Ctrl-c to end your program in the terminal window. In this situation, turning the Scribbler 2 off or pressing the reset button resets the robot.

Scribbler-based Examples

In class we may discuss the following programs:

Summary

The readings identify three basic types of loops: for, while, and do..while. Program three-loops.c uses each of these constructions to print the numbers 1 to 10 on separate lines

Although the loops have many similarities, one type of loop may seem to fit a circumstance more naturally than another.

The for loop often focuses on the progression of one or more control variables. In what follows, the code emphasizes the values for i during the running of the code.

/* for loop */
printf ("for loop\n");
for (i = start; i <= end; i++)
{
  printf ("%5d", i);
} // for i
printf ("\n");

A while loop often emphasizes the condition under which the loop will continue. Updating variables takes place in the body of the loop and may be complex.

/* while loop */
printf ("while loop\n");
i = start;
while (i <= end)
{
  printf ("%5d", i);
  i++;
} // while
printf ("\n");

In contrast to for and while which may skip the loop completely if the condition is not satisfied, the do..while always executes its loop body at least once.

/* do while */
printf ("do..while loop\n");
i = start;
do
{
  printf ("%5d", i);
  i++;
} while (i <= end);
printf ("\n");

Self-Checks

  1. Copy three-loops.c to your account, compile and run it, and be sure you understand how each loop works. Also, explain the purpose of the line printf ("\n");. Is this statement inside the loop or not? Why?
  2. In the three-loops.c program, change the initialization of start to 11, recompile, and rerun the program. Describe what happens and explain why.