For loops
Syntax#
- for(init; condition; increment){ content_code(); } // general syntax
- for(int i = 0; i < numberRuns; ++i){ actions_with(i); } // run an action for a numberRuns times
- for(int i = 0; i < sizeof(array); ++i){ actions_with(array[i]); } // iteration over an array
General for loop
Most programming languages support the for
-loop control structure.
It is generally implemented in this way:
for(init; condition; increment){
content_code();
}
The above pseudocode is identical with the pseudocode below:
init;
start_loop:
if(condition){
content_code();
increment;
goto start_loop;
}
This shows that:
init
is run before the loop, used to initialize things for running that loop- In some programming languages like Java, variables can be declared in
init
, and the scope of the declared variables will be limited to that loop.
- In some programming languages like Java, variables can be declared in
condition
is a condition to determine when the loop can be run. If this evaluates tofalse
, the loop will stop executing.increment
is usually a statement used to manipulate parameters used incondition
, so whenincrement
is run a certain number of times,condition
becomesfalse
and the loop breaks.content_code()
is the core code to be run within the loop.