O'Reilly logo

Practical C Programming, 3rd Edition by Steve Oualline

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required