Examples Using the for Statement

The following for statement prints the value of count 20 times. The for statement initially sets the value of count to 1. After each iteration of the statement, count is incremented.

for (count = 1; count <= 20; count++)
   printf("count = %d\n", count);

The following sequence of statements accomplishes the same task. Note the use of the while statement instead of the for statement.

count = 1;
while (count <= 20)
{
   printf("count = %d\n", count);
   count++;
}

The following for statement does not contain an initialization expression:

for (; index > 10; --index)
{
   list[index] = var1 + var2;
   printf("list[%d] = %d\n", index, list[index]);
}

The following for statement will continue running until scanf receives the letter e.

for (;;)
{
   scanf("%c", &letter);
   if (letter == '\n')
      continue;
   if (letter == 'e')
      break;
   printf("You entered the letter %c\n", letter);
}

The following for statement contains multiple initializations and increments. The comma operator makes this construction possible.

for (i = 0, j = 50; i < 10; ++i, j += 50)
{
    printf("i = %2d and j = %3d\n", i, j);
}

The following example shows a nested for statement. It prints the values of an array having the dimensions [5][3].

for (row = 0; row <5; row++)
   for (column=0; column < 3; column++) 
      printf("%d\n", table[row][column]);

The outer statement is processed as long as the value of row is less than 5. Each time the outer for statement is executed, the inner for statement sets the initial value of column to zero and the statement of the inner for statement is executed 3 times. The inner statement is executed as long as the value of column is less than 3.



for Statement
break Statement
continue Statement