Chapter 8. More Control Statements

Grammar, which knows how to control even kings...

Molière

for Statement

The for statement allows the programmer to execute a block of code for a specified number of times. The general form of the for statement is:

for (initial-statement; condition; iteration-statement)    
    body-statement;

This statement is equivalent to:

initial-statement; 
while (condition) {     
    body-statement;    
    iteration-statement; 
}

For example, Example 8-1 uses a while loop to add five numbers.

Example 8-1. total5w/totalw.c
#include <stdio.h>

int total;      /* total of all the numbers */
int current;    /* current value from the user */
int counter;    /* while loop counter */

char line[80];  /* Line from keyboard */

int main() {
    total = 0;

    counter = 0;
    while (counter < 5) {
        printf("Number? ");

        fgets(line, sizeof(line), stdin);
        sscanf(line, "%d", &current);
        total += current;

        ++counter;
    }
    printf("The grand total is %d\n", total);
    return (0);
}

The same program can be rewritten using a for statement as shown in Example 8-2.

Example 8-2. total5f/total5f.c
#include <stdio.h>

int total;      /* total of all the numbers */
int current;    /* current value from the user */
int counter;    /* for loop counter */

char line[80];  /* Input from keyboard */

int main() {
    total = 0;
    for (counter = 0; counter < 5; ++counter) {
        printf("Number? ");

        fgets(line, sizeof(line), stdin);
        sscanf(line, "%d", &current);
        total += current;
    }
    printf("The grand total is %d\n", total);
    return (0);
}

Note that counter goes from to 4. Ordinarily, ...

Get Practical C Programming, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.