When we want to execute a sequence of instructions a specific number of times, it is possible to set up and use one of the basic loops, such as the while one below. Before the loop is begun, the counter called num is initialized to the first value desired. The keyword while is followed by an execution condition -- if it evaluates to true, the statement following is executed; otherwise, it is not. The body of the loop consists of a compound statement, delimited by curly brackets, and must include two parts to be useful: (1) one or more statements to do something, here to print the value of num; (2) an assignment statement to change the value of num so that the execution condition eventually evaluates to false, so that the execution of the loop will be terminated.
/* Print the first five Natural numbers */
num = 1; /* Initialize counter */
while (num <= 5) /* Termination check */
{
printf("%d\n", num);
num = num + 1; /* Increment counter */
}
For a situation such as this, C provides a programming short-cut known as the for loop. The one following performs the same task as the loop above, but using only two lines of code.
/* Print the first five Natural numbers */
for (num = 1; num <= 5; num++)
printf("%d\n", num);
The general format for a for statement would be as follows:
for (counter initialization; boolean termination check; counter alteration) statement;
Both the initialization and alteration expressions can be lists using the comma operator, e.g., i++, j++, while the boolean check can be compound, e.g., i < 100 && j > 0 .
The above for loop uses the ++ unary increment operator which increases the variable's value by one. If the desired values are not consecutive, code can be written to generate them if the difference between them is calculable. The next segment calculates and prints even numbers using related natural numbers in the counter. Notice, for the code segment on the left, that since more than one statement needs to be repeated, they are bounded by curly brackets.
/* Print the first five even Natural numbers */
for (i = 1; i <= 5; i++)
{
num = i * 2;
printf("%d\n", num);
}
for (num = 2; num <= 10; num = num + 2)
printf("%d\n", num);
It is also possible to use a negative increment (i.e., decrement) using the -- operator or an assignment statement.
/* Print the first five odd Natural numbers backwards */
for (i = 5; i >= 1; i--)
{
num = i * 2 - 1;
printf("%d\n", num);
}
for (num = 9; num >= 1; num = num - 2)
printf("%d\n", num);