CSC 161 Grinnell College Fall, 2011 Imperative Problem Solving and Data Structures

# counting-loop.c: A basic program about loops

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;
}

```

### Commentary on the `counting-loop.c` program

A `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++);`

• 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.

This document is available on the World Wide Web as

```http://www.cs.grinnell.edu/~
```