Home  >  Article  >  Backend Development  >  What are the different variations of for loop iteration?

What are the different variations of for loop iteration?

WBOY
WBOYforward
2023-09-07 14:53:02913browse

What are the different variations of for loop iteration?

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);

Variation 1

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.

Variation 2

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.

Variation 3

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 == &#39;A&#39;)
      break;
}

Variation 4

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==&#39; &#39;; 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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete