Document Information

DocuDocument Title
Document Number & Revision> 403 - 0005 - 1.0
Release Date April  21, 2019
Document Status> Rev 1: Original Document



The for loop, sometimes known as the loop, which in some ways is similar to the while loop is a usefull tool to have controlled loops within your code. The difference is that the initialisation takes place within the declaration. This loop is very usefull especially when the form is used to store or index through data, gathering samples from an analog input or accessing an EEPROM, etc.

This topic is introductory, and should be read in conjunction with other topics in this series of training documents.


The for loop or the 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.


The for...loop has valueable implications for your code when applied to real life applications.