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
- King: Sections 6.1-6.5, pages 99-120
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.
Loop Header
Example: for (i = 1; i < 11; i++)
- variable initialization
-
Example:
i = 1This 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 < 11This 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
iis 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
- Nested loops are loops that have another loop in the first loop's body. This means that for every iteration of the outer loop, the inner loop is executed as a complete loop.
- When looking at nested loops, it is important that the inner loop must have its variables initialized inside the initialization statement. If this is not the case, then the first iteration of the outer loop leads to the inner loop variable(s) being changed, and upon the second iteration of the outer loop, the inner loop's continue expression depends on the old value of the variable(s) and may not cover the full range of cases desired.
- In the current example, the inner loop is executed a certain number of times based on the outer loop, and a new line for the next row of asterisks is only included in the outer loop body.
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:-
follower-1.c, which follows an object usingifstatements, -
follower-2.c, which follows an object using aswitchstatement, and -
coins.c, which simulates several coin flips.
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
-
Copy
three-loops.cto your account, compile and run it, and be sure you understand how each loop works. Also, explain the purpose of the lineprintf ("\n");. Is this statement inside the loop or not? Why? -
In the
three-loops.cprogram, change the initialization ofstartto 11, recompile, and rerun the program. Describe what happens and explain why.
