Examples of for statements

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.

int count;
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.

int 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. The first comma in the for expression is a punctuator for a declaration. It declares and initializes two integers, i and j. The second comma, a comma operator, allows both i and j to be incremented at each step through the loop.

for (int i = 0,
j = 50; i < 10; ++i, j += 50)
{
   cout << "i = " << i << "and j = " << j
   << endl;
}

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.



[ Top of Page | Previous Page | Next Page | Contents | Index ]