The general form of the for statement is as follows −
for (initialization; condition; operation) statement;
Initialization is an assignment statement used to set loop control variables.
The condition is a relational expression that determines when the loop exits.
The action defines how the loop variable changes each time the loop repeats.
In a for loop, the conditional test is executed at the top of the loop. This means that the code inside the loop may not be executed when the condition is false.
Start with the following example:
x = 10; for (y=10; y != x; ++y) printf (“ %d”, y);
This includes the comma operator. Through the comma operator, a variation of the for loop can be implemented, as shown in the following example −
for(x=0, y=0; x+y < 10; ++x);
Here, both x and y control the loop.
This includes the missing parts of the loop definition. An interesting feature of the for loop is that the loop definition part does not need to exist.
For example,
for (x=0; x!=456; ) scanf ("%d", &x);
Here, each time the loop repeats, x is tested to check if it is equal to 456. When 456 is entered, the loop condition becomes false and the loop is terminated.
This includes infinite loops. If all parts of the loop definition are missing, an infinite loop is created. The break statement is used to break out of a loop, as shown in the following example −
for(;;){ ch = getchar(); if(ch == 'A') break; }
This includes for loops without a body. The body of the for loop can also be empty. This improves the efficiency of some code.
For example,
Let us remove leading spaces from the stream pointing to str −
for ( ; *str==' '; str++) ;
Another application of the loop is a time delay of an empty body as given below The example is shown −
for (t=0; t<1000; t++);
The above is the detailed content of What are the different variations of for loop iteration?. For more information, please follow other related articles on the PHP Chinese website!