| CSC 161 | Grinnell College | Spring, 2012 |
| Imperative Problem Solving and Data Structures | ||
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.
/*
* Program using a simple loop that prints the numbers from 1 to 10.
*/
#include <stdio.h>
int
main()
{
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;
}
counting-loop.c programA for loop is composed of an initializing statement, and
a body of actions. The initializing statement has three components.
Example: for (i = 1; i < 11; i++);
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.
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!
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.
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.
This document is available on the World Wide Web as
http://www.walker.cs.grinnell.edu/courses/161.sp12/modules/cond-loops-testing/counting-loop-annotated.shmtml
|
created 28 July 2011 by April O'Neill last full revision 29 July 2011 by April O'Neill minor editing 26 September 2011 by Henry M. Walker |
|
| For more information, please contact Henry M. Walker at walker@cs.grinnell.edu. |