Introduction
The for loop or the for...next loop, similar to the while(condition) loop is initialized within the declaration. This allows for a loop condition or a repeating condition to be initialized,
which repeats a certain task or set of tasks until the condition keeping the loop going is no longer true. When the loop is initialized, the loop has the following conditions.
initial expression |
The initial expression intialised the loop, setting a starting point to the loop |
condition_expression |
The condition expression is what determines when the loop exits, and can be determined by the usual bitwise operators. |
change expression |
The change condition is affected during each loop by either incrementing or decrementing the loop. |
Example Code Sample
The example below shows how to create and initialize a for... loop.
/*
for loop
*/
for (initial expression; condition_expression; change expression){
...tasks...
}
In the example below, the for loop is being used to toggle an LED 5 times. This same loop can also be used to gather 5 samples from an analog input as well for example.
It can be used to achieve simple tasks or more sophisticated tasks, depending on the need.
/*
for loop
*/
int i;
for (i=1; i<5; i++){
Delay_ms(500);
LED=~LED
}
The most valueable aspect of the for...loop is the ability to use the "current count" of the loop as an index value. This enables the for...loop to be used in arrays where either
the entire array needs to be updated or specific elements with the array need to be updated, changed or deleted.
Conclusion
The for...loop has valueable implications for your code when applied to real life applications.