What are different variations of for loop iterations?

The general form of the for statement is as follows −

for (initialization; condition; operation)
  • Initialization is an assignment statement which is used to set the loop control variable.

  • Condition is a relational expression that determines when the loop exits.

  • The operation defines that how the loop variable changes each time when the loop is repeated.

  • In for loops, the conditional test is performed at the top of the loop. This means that the code inside the loop may not be executed when the condition is false.

To begin with as in the following example −

x = 10;
for (y=10; y != x; ++y)
printf (“ %d”, y);

Variation 1

This includes the comma operator. A variant of the for loop is made possible by the comma operator, as in the following example −

for(x=0, y=0; x+y < 10; ++x);

Here, both x and y control the loop.

Variation 2

This includes the missing pieces of the loop definition. An interesting trait of the for loop is that pieces of the loop definition need not be there.

For example,

for (x=0; x!=456; )
scanf ("%d", &x);

Here, when each time the loop repeats, x is tested to check if it equals 456. The loop conditions become false and terminates the loop, when 456 is entered.

Variation 3

This includes the infinite loop. If all of the pieces in the loop definition are missing, an infinite loop is created. The break statement is used to break out of the loop, as in an example given below −

   ch = getchar();
   if(ch == 'A')

Variation 4

This includes for Loops with No Bodies. The body of the for loop may also be empty. This improves the efficiency of some code.

For example,

Let us remove the leading spaces from the stream pointed to by str −

for ( ; *str==' '; str++) ;

Another application of a loop is a Time delay with an empty body, as shown in an example given below −

for (t=0; t<1000; t++);