The most complex loop in C is the for loop. The for
construct, as it was developed in earlier computer languages such as
BASIC and Pascal, was intended to behave in the following way:
For all values of variable from value1 to value2, in
steps of value3, repeat the following sequence of commands...
The for loop in C is much more versatile than its counterpart in
those earlier languages. The for loop looks like this in C:
for (initialization; condition; increment)
{
do something;
}
In normal usage, these expressions have the following significance.
initialization
This is an expression that initializes the control variable, or
the variable tested in the condition part of the for
statement. (Sometimes this variable is called the loop's
index.) The initialization part is only carried out once
before the start of the loop. Example: index = 1.
condition
This is a conditional expression that is tested every time through the
loop, just as in a while loop. It is evaluated at the
beginning of every loop, and the loop is only executed if the
expression is true. Example: index <= 20.
increment
This is an expression that is used to alter the value of the control
variable. In earlier languages, this usually meant adding or subtracting
1 from the variable. In C, it can be almost anything. Examples:
index++, index *= 20, or index /= 2.3.
For example, the following for loop prints out the integers from
1 to 10:
int my_int;
for (my_int = 1; my_int <= 10; my_int++)
{
printf ("%d ", my_int);
printf("\n");
}
The following example prints out all prime numbers between 1 and the
macro value MAX_INT. (A prime numbers is a number that cannot be
divided by any number except 1 and itself without leaving a remainder.)
This program checks whether a number is a prime by dividing it by all
smaller integers up to half its size. (See Preprocessor directives,
for more information on macros.)
#include <stdio.h>
#define MAX_INT 500
#define TRUE 1
#define FALSE 0
int main ()
{
int poss_prime;
for (poss_prime = 2; poss_prime <= MAX_INT; poss_prime++)
{
if (prime(poss_prime))
{
printf ("%d ", poss_prime);
}
}
printf("\n\n");
return 0;
}
prime (int poss_prime) /* check whether poss_prime is prime */
{
int poss_factor;
for (poss_factor = 2; poss_factor <= poss_prime/2; poss_factor++)
{
if (poss_prime % poss_factor == 0)
{
return (FALSE);
}
}
return (TRUE);
}
The program should print the following sequence of integers: