Programmers often need to stop a loop when a specific condition occurs. Text-based languages include statements that allow both For Loops and While Loops to exit upon a specified condition. For example, in the following sample C code, a the loop is programmed to iterate 50 times (from 0 to 49). However, the loop stops execution using the Break function after 11 iterations, when i = 10.
i = 0;
for (i = 0; i < 50; i++)
if (i == 10)
A LabVIEW programmer who needs to iterate over all the elements in an array often uses a For Loop because it allows the auto-indexing of the array. Typical LabVIEW code looks like Figure 3.
Figure 3. LabVIEW Code for a For Loop
While this solution is functionally correct, the For Loop visits every element in the array, even if the exit condition occurs in an early iteration of the loop. For greater efficiency, you can instead use a While Loop (see Figure 4). This solution, which is more complex and requires more code, iterates over the array until the exit condition occurs or the end of the array is reached. As shown in Figure 1, a For Loop configured for a break condition is much simpler and more elegant solution.
Figure 4. A While Loop Configured To Index an Array
You also can use a While Loop to search an array; when you have found your item of interest, the loop stops executing. If the item is not in the array, the result is an infinite loop.
Figure 5. While Loop Potentially Leading to an Infinite Loop
A better solution is to use a For Loop configured for a break. If the item of interest is not found in the array, the loop stops after N iterations.
Figure 6. For Loops Mitigate the Chance of an Infinite Loop