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

What are the different variations of for loop iteration?

WBOY
Release: 2023-09-07 14:53:02
forward
972 people have browsed it

What are the different variations of for loop iteration?

The general form of the for statement is as follows −

for (initialization; condition; operation)
statement;
Copy after login
  • 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);
Copy after login

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);
Copy after login

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);
Copy after login

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;
}
Copy after login

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++) ;
Copy after login

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++);
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template