Knowledge Base
...
Applied PIC Micro Development
PIC Programming

"For Next"

5min

Synopsis

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

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

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 for 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.

C


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. 

C


The most valuable 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 within the array need to be updated, changed, or deleted.

Conclusion

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