The for loop is a step-by-step means of performing repetitive actions. Let's take a closer look at how it works.
Typically, parts of a for loop perform the following steps:
1. Setting the initial value.
2. Performing a condition check to continue the loop.
3. Performing a loop action.
4. Updating the value (s) used in the test condition.
and then steps 2-4 are repeated until the condition is satisfied. As soon as the condition becomes false, the loop stops its operation and the statement following the for loop operator is executed.
Let us return to the general form of writing the loop operator and analyze in more detail all parts
for (/*part 1*/; /*part 2*/; /*part 3*/ )
{
/* body of loop*/;
}
Part 1
responsible for setting the initial value of the loop variable (counter), ends with a semicolon
For example :
1) i=0; //assign the initial value equal to zero to the loop variable i. With such a record, the variable i must be declared before the loop
2) int i=0; //i can be declared immediately in the loop header, but
// in this case, after the loop runs, it will be erased from memory
3) ; // there is no initialization and declaration of the loop variable in general,
// in this case, it can be declared before the loop
Part 2
this is a condition for continuing the for loop, it is checked for truth.
i<=10 // the loop will run as long as i is less than or equal to 10.
The condition can be any
Part 3
changes the value of the counter variable. Without this value, the loop will be considered infinite
i++ //after each execution of the loop body, 1 will be added to the loop variable i
Let's practice the for loop header entry