next up previous contents index
Next: switch Up: Control Structures Previous: do   Contents   Index


for

The C for statement is a very general looping construction, and has been copied by many other programming languages. A simple use might look like

  
for (i=0; i<10; i=i+1) {
  /*  body of the loop goes here  */
}
The parentheses following the for keyword contain three expressions, of which the second is interpreted as a logical expression. The first expression (the initialization statement) is evaluated at the start, then the second expression (the continuation condition) is evaluated. If it is true, the body of the loop is executed, then the third expression (the increment statement) is evaluated. The continuation condition is checked again, and if still true, the body of the loop is executed once more. This process continues until the continuation condition fails or a break statement is met. The for loop above is equivalent to

  
i = 0;
while (i < 10) {
  /*  body of the loop  */
  i = i+1;
}
The three expressions can be arbitrary, even empty. (If the continuation condition is empty, it will be interpreted as true, so the loop will run forever, unless a break statement is met.)

  
/*  write out the part of the string a, up to but excluding 
    the first occurrence of the character 'R'  */
for (i=0; a[i] != 'R'; i=i+1) {
  printf("%c", a[i]);
}


next up previous contents index
Next: switch Up: Control Structures Previous: do   Contents   Index
CATAM admin 2010-02-23