For Loops

For loops are used very commonly. The for loop is declared as follows:
    for ( <initialization>; <execution condition>; <update operation> )
    {
        /*code that is repeated*/
    }

initialization is performed once when the loop is started. This is normally used to set the value of a variable at the beginning of the loop. The for loop executes until the execution condition is false. The update operation is performed after each time the code in the braces is executed. The sequence of operations is as follows:

1.  perform initialization
2.  check execution condition and quit loop if it is false
3.  execute code contained within the braces
4.  perform the update operation
5.  go to step 2 and repeat
An example for loop is shown below. It adds the numbers from 1 to 100:

#include <stdio.h>

int main(int argc, char* argv[])
{
    int i, sum = 0;
    
    /*the value of i is initialized to 1, and each time the loop
      is executed, i is increased by 1.  The loop executes as long
      as i is less than or equal to 100.*/
    for ( i = 1; i <= 100; i++ /*this increments i by 1*/)
    {
        sum = sum + i;
    }

    printf("The sum of the numbers from 1 to 100 is: %d\n", sum);

    return 0;
}

next


 home                      table of contents                      about