Company Events Academic Community Support Solutions Products & Services Contact NI MyNI

For Loop and While Loop Structures

LabVIEW 8.5 Help
August 2007

NI Part Number:
371361D-01

»View Product Info
Download Help (Windows Only)

Use the For Loop and the While Loop to control repetitive operations.

Note   If you open a refnum inside a For Loop or While Loop, close that refnum for each iteration of the loop. Otherwise, LabVIEW repeatedly allocates memory for the refnum and does not free the memory until the VI finishes running.

For Loops

A For Loop, shown as follows, executes a subdiagram a set number of times.

The count terminal, shown as follows, is an input terminal whose value indicates how many times to repeat the subdiagram.

Set the count explicitly by wiring a value from outside the loop to the left or top side of the count terminal, or set the count implicitly with auto-indexing.

The iteration terminal, shown as follows, is an output terminal that contains the number of completed iterations.

The iteration count always starts at zero. During the first iteration, the iteration terminal returns 0. If the iteration count exceeds 2,147,483,647, or 231, the iteration terminal will remain at 2,147,483,647 for all further iterations. If you need to keep count of more than 2,147,483,647 iterations, you can use shift registers with a greater integer range.

Both the count and iteration terminals are 32-bit signed integers. If you wire a floating-point or fixed-point number to the count terminal, LabVIEW rounds it and coerces it to within range. If you wire 0 or a negative number to the count terminal, the loop does not execute and the outputs contain the default data for that data type.

Add shift registers to the For Loop to pass data from the current iteration to the next iteration.

For Loops with Conditional Terminals

You can add a conditional terminal to configure a For Loop to stop when a Boolean condition or an error occurs. A For Loop with a conditional terminal executes until the condition occurs or until all iterations complete, whichever happens first. For example, if you want a loop to execute a set number of times unless an error occurs, you can use a For Loop with a conditional terminal and wire an error cluster to the conditional terminal, shown as follows.

To add or remove a conditional terminal in a For Loop, right-click the loop border and select Conditional Terminal from the shortcut menu. If you add a conditional terminal to a For Loop, the conditional terminal appears in the bottom right of the loop and the count terminal appearance changes, as shown in the following illustration.

You cannot press the <Delete> key to remove a conditional terminal. In a For Loop with a conditional terminal, you must wire the conditional terminal and either wire a numeric value to the count terminal or auto-index an input array.

The number wired to the count terminal or the number of elements in the auto-indexed input array acts as the maximum number of loop iterations that complete only if the condition wired to the conditional terminal never occurs. If you want a loop to iterate until a condition occurs with no maximum number of iterations, use a While Loop instead.

To configure a conditional terminal, wire Boolean data, such as a Boolean control or an output from a Comparison function, to the conditional terminal. You also can wire an error cluster to the conditional terminal. The default behavior and appearance of the conditional terminal is Stop if True, shown as follows.

If a conditional terminal is Stop if True, the For Loop executes the subdiagram until the conditional terminal receives a TRUE value or until the For Loop completes the number of iterations wired to the count terminal or auto-indexed from an input array. You can change the behavior and appearance of the conditional terminal by right-clicking the terminal and selecting Continue if True, shown as follows, from the shortcut menu.

If a conditional terminal is Continue if True, the For Loop executes the subdiagram until the conditional terminal receives a FALSE value. You also can use the Operating tool to click the conditional terminal to change the condition.

Note  If you wire the conditional terminal in a For Loop, you cannot predetermine the number of iterations the loop executes. You can determine the number of iterations the loop completes by auto-indexing an output array and checking the number of elements after the loop executes or by wiring an indicator to the loop iteration terminal and checking the count after the loop executes.

While Loops

Similar to a Do Loop or a Repeat-Until Loop in text-based programming languages, a While Loop, shown as follows, executes a subdiagram until a condition occurs.

The While Loop executes the subdiagram until the conditional terminal, an input terminal, receives a specific Boolean value. The conditional terminal in a While Loop behaves the same as in a For Loop with a conditional terminal. However, because the For Loop also includes a set iteration count, it does not run infinitely if the condition never occurs. The While Loop does not include a set iteration count and runs infinitely if the condition never occurs.

If a conditional terminal is Stop if True, you place the terminal of a Boolean control outside a While Loop, and the control is FALSE when the loop starts, you cause an infinite loop, as shown in the following example. You also cause an infinite loop if the conditional terminal is Continue if True and the control outside the loop is set to TRUE.

Changing the value of the control does not stop the infinite loop because the value is only read once, before the loop starts. To stop an infinite loop, you must abort the VI by clicking the Abort Execution button on the toolbar.

You also can perform basic error handling using the conditional terminal of a While Loop. When you wire an error cluster to the conditional terminal, only the TRUE or FALSE value of the status parameter of the error cluster passes to the terminal. Also, the Stop if True and Continue if True shortcut menu items change to Stop if Error and Continue while Error.

The iteration terminal, shown as follows, is an output terminal that contains the number of completed iterations.

The iteration count always starts at zero. During the first iteration, the iteration terminal returns 0.

Add shift registers to the While Loop to pass data from the current iteration to the next iteration.

Controlling Timing

By default, LabVIEW executes loops and block diagrams as quickly as possible. However, you might want to control the speed at which a process executes, such as the speed at which data values are plotted to a chart. You can use a Wait function in the loop to specify the amount of time in milliseconds before the loop re-executes.

Auto-Indexing Loops

If you wire an array to a For Loop or While Loop input tunnel, you can read and process every element in that array by enabling auto-indexing.

If you wire an array to a For Loop or While Loop, you can read and process every element in that array by enabling auto-indexing. When you wire an array from an external node to an input tunnel on the loop border and enable auto-indexing on the input tunnel, elements of that array enter the loop one at a time, starting with the first element. When auto-indexing is disabled, the entire array is passed into the loop. When you auto-index an array output tunnel, the output array receives a new element from every iteration of the loop. Therefore, auto-indexed output arrays are always equal in size to the number of iterations. For example, if the loop executes 10 times, the output array has 10 elements. If you disable auto-indexing on an output tunnel, only the element from the last iteration of the loop passes to the next node on the block diagram.

Right-click the tunnel at the loop border and select Enable Indexing or Disable Indexing from the shortcut menu to enable or disable auto-indexing. Auto-indexing for While Loops is disabled by default.

A bracketed glyph appears on the loop border to indicate that auto-indexing is enabled. The thickness of the wire between the output tunnel and the next node also indicates the loop is using auto-indexing. The wire is thicker when you use auto-indexing because the wire contains an array instead of a scalar.

The loop indexes scalar elements from 1D arrays, 1D arrays from 2D arrays, and so on. The opposite occurs at output tunnels. Scalar elements accumulate sequentially into 1D arrays, 1D arrays accumulate into 2D arrays, and so on.

Auto-Indexing to Set the For Loop Count

If you enable auto-indexing on an array wired to a For Loop input terminal, LabVIEW sets the count terminal to the array size so you do not need to wire the count terminal. Because you can use For Loops to process arrays one element at a time, LabVIEW enables auto-indexing by default for every array you wire to a For Loop. You can disable auto-indexing if you do not need to process arrays one element at a time.

If you enable auto-indexing for more than one tunnel or if you wire the count terminal, the actual number of iterations becomes the smaller of the choices. For example, if two auto-indexed arrays enter the loop, with 10 and 20 elements respectively, and you wire a value of 15 to the count terminal, the loop still only executes 10 times, indexing all elements of the first array but only the first 10 elements of the second array. As another example, if you plot data from two sources on one graph and you want to plot the first 100 elements, wire 100 to the count terminal. However, if the smaller data source includes only 50 elements, the loop executes 50 times and indexes only the first 50 elements of each data source. Use the Array Size function to determine the size of arrays.

Auto-Indexing with While Loops

If you enable auto-indexing for an array entering a While Loop, the While Loop indexes the array the same way as a For Loop. However, the number of iterations a While Loop executes is not limited by the size of the array because the While Loop iterates until a specific condition occurs. When a While Loop indexes past the end of the input array, the default value for the array element type passes into the loop. You can prevent the default value from passing into the While Loop by using the Array Size function. The Array Size function indicates how many elements are in the array. Set up the While Loop to stop executing when the number of iterations equals the array size.

Caution  Because you cannot determine the size of the output array in advance, enabling auto-indexing for the output of a For Loop is more efficient than that of a While Loop. Iterating too many times can cause your system to run out of memory.

Using Loops to Build Arrays

In addition to using loops to read and process elements in an array, you also can use the For Loop and the While Loop to build arrays. Wire the output of a VI or function in the loop to the loop border. If you use a While Loop, right-click the resulting tunnel and select Enable Indexing from the shortcut menu. If you use a For Loop, indexing is enabled by default. The output of the tunnel is an array of every value the VI or function returns after each loop iteration.

Refer to the labview\examples\general\arrays.llb for examples of building arrays.

Shift Registers and the Feedback Node in Loops

Use shift registers or the Feedback Node with For Loops or While Loops to transfer values from one loop iteration to the next.

Shift Registers

Use shift registers when you want to pass values from previous iterations through the loop to the next iteration. A shift register appears as a pair of terminals, shown as follows, directly opposite each other on the vertical sides of the loop border.

The terminal on the right side of the loop contains an up arrow and stores data on the completion of an iteration. LabVIEW transfers the data stored in the right terminal of the shift register to the left terminal. The loop then uses the data from the left terminal as the initial values for the next iteration. This process continues until all iterations of the loop execute. After the loop executes, the terminal on the right side of the loop returns the last value stored in the shift register.

Create a shift register by right-clicking the left or right border of a loop and selecting Add Shift Register from the shortcut menu.

A shift register transfers any data type and automatically changes to the data type of the first object wired to the shift register. The data you wire to the terminals of each shift register must be the same type.

You can add more than one shift register to a loop. If you have multiple operations that use previous iteration values within a loop, use multiple shift registers to store the data values from those different processes in the structure, as shown in the following block diagram.

In the previous block diagram, the upper right shift register terminal transfers 2, the sum of 0 and 2 in the first iteration, to the upper left terminal as the initial value for the second iteration of the addition operation. The lower right terminal transfers 2, the product of 1 and 2 in the first iteration, to the lower left terminal as the initial value for the second iteration of the multiplication operation. The second iteration adds 2 and 2 and transfers the outcome, 4, to the upper left terminal for the third iteration. The second iteration also multiplies 2 and 4 and transfers the outcome, 8, to the lower left terminal for the third iteration. After ten iterations, the upper right terminal transfers the final outcome of the addition operation to the upper indicator and the lower right terminal transfers the final outcome of the multiplication operation to the lower indicator.

Initializing Shift Registers

Initializing a shift register resets the value the shift register passes to the first iteration of the loop when the VI runs. Initialize a shift register by wiring a control or constant to the shift register terminal on the left side of the loop, as shown in the following block diagram.

In the previous block diagram, the For Loop executes five times, incrementing the value the shift register carries by one each time. After five iterations of the For Loop, the shift register passes the final value, 5, to the indicator and the VI quits. Each time you run the VI, the shift register begins with a value of 0.

If you do not initialize the shift register, the loop uses the value written to the shift register when the loop last executed or, if the loop has never executed, the default value for the data type.

Use an uninitialized shift register to preserve state information between subsequent executions of a VI. The following block diagram shows an uninitialized shift register.

In the previous block diagram, the For Loop executes five times, incrementing the value the shift register carries by one each time. The first time you run the VI, the shift register begins with a value of 0, which is the default value for a 32-bit integer. After five iterations of the For Loop, the shift register passes the final value, 5, to the indicator, and the VI quits. The next time you run the VI, the shift register begins with a value of 5, which was the last value from the previous execution. After five iterations of the For Loop, the shift register passes the final value, 10, to the indicator. If you run the VI again, the shift register begins with a value of 10, and so on. Uninitialized shift registers retain the value of the previous iteration until you close the VI.

Stacked Shift Registers

Stacked shift registers let you access data from previous loop iterations. Stacked shift registers remember values from multiple previous iterations and carry those values to the next iterations. To create a stacked shift register, right-click the left terminal and select Add Element from the shortcut menu.

Stacked shift registers can occur only on the left side of the loop because the right terminal transfers the data generated from only the current iteration to the next iteration, as shown in the following block diagram.

If you add another element to the left terminal in the previous block diagram, values from the last two iterations carry over to the next iteration, with the most recent iteration value stored in the top shift register. The bottom terminal stores the data passed to it from the previous iteration.

Replacing Shift Registers with Tunnels

Replace shift registers with tunnels by right-clicking the shift register and selecting Replace with Tunnels from the shortcut menu when you no longer need to transfer values from one loop iteration to the next.

If you replace an output shift register terminal with a tunnel on a For Loop, the wire to any node outside the loop breaks because the For Loop enables indexing by default. Right-click the tunnel and select Disable Indexing at Source from the shortcut menu to disable indexing and automatically correct the broken wire. If you want indexing enabled, delete the broken wire and the indicator terminal, right-click the tunnel, and select Create Indicator from the shortcut menu.

Replacing Tunnels with Shift Registers

Replace tunnels with shift registers by right-clicking the tunnel and selecting Replace with Shift Register from the shortcut menu when you want to transfer values from one loop iteration to the next. If no tunnel exists on the loop border opposite of the tunnel you right-clicked, LabVIEW automatically creates a pair of shift register terminals. If a tunnel exists on the loop border opposite of the tunnel you right-clicked, LabVIEW replaces the tunnel you right-clicked with a shift register terminal, and the cursor becomes a shift register icon, shown as follows.

Click a tunnel on the opposite side of the loop to replace the tunnel with a shift register or click the block diagram to place the shift register on the loop border directly across from the other shift register terminal. If the shift register terminal appears behind a tunnel, the shift register is not wired.

If you convert a tunnel with indexing enabled to a shift register on a While Loop, the wire to any node outside the loop breaks because shift registers cannot auto index. Delete the broken wire, wire the output wire located to the right of the shift register to another tunnel, right-click the tunnel, select Enable Indexing from the shortcut menu, and wire the tunnel to the node.

Feedback Node

The Feedback Node, shown as follows, operates similarly to shift registers in loops.

Like a shift register, the Feedback Node stores data when the loop completes an iteration, sends the stored data to the next loop iteration, and transfers the data type to the next loop iteration. The next iteration reads the data, writes a new value to the data, and sends it through the loop again. This process continues until the loop execution completes. The Feedback Node stores data from only the previous iteration. If you wire a value to the initializer terminal, shown as follows, the Feedback Node initializes to that value on the first call of the VI in an execution or each time a loop executes, depending on whether you leave the initializer terminal on the node or move the terminal to the left edge of a loop.

Initializing the Feedback Node on Loop Execution

To initialize a Feedback Node when a loop executes, click and drag the initializer terminal to the left edge of a loop that contains a Feedback Node or the left edge of a loop in a group of nested structures that contains the Feedback Node. The Feedback Node then initializes before the first iteration of each execution of the loop. You also can right-click the initializer terminal and select Move Initializer One Loop Out or Move Initializer One Loop In from the shortcut menu to move the initializer terminal. You must wire an initial value to the initializer terminal if you move it to the left edge of a loop. If the initializer terminal is on the edge of the outermost or innermost loop, as in the following block diagram, LabVIEW dims the corresponding option to Move Initializer One Loop Out or Move Initializer One Loop In in the shortcut menu.

In the previous block diagram, although the Feedback Node is in the For Loop, the initializer terminal is on the edge of the outermost While Loop. Thus, the Feedback Node initializes to the input value 2 every time the While Loop executes, whereas the outcome of the Increment function builds on previous values for each For Loop execution. Separating the Feedback Node and initializer is useful in nested Case structures when you want the Feedback Node to execute only in certain cases.

Globally Initializing the Feedback Node

If you do not move the initializer terminal to the left edge of a loop, the Feedback Node globally initializes. You can use a Feedback Node that globally initializes anywhere on the block diagram. If a Feedback Node globally initializes and you set an initial value, the Feedback Node initializes to that value on the first call of the VI in an execution. If you do not wire an input value to the initializer terminal, the initial input of the Feedback Node for the first execution is the default value for the data type. Each time the VI runs after the first execution, the initial value is the last value from the previous execution. The following block diagrams show the differences in value from execution to execution for a Feedback Node with a wired initializer terminal and a Feedback Node with an unwired initializer terminal.

First Execution Second Execution
Iteration End Value Iteration End Value
0 3 0 3
1 4 1 4
2 5 2 5
3 6 3 6

Since the Feedback Node in the previous block diagram reinitializes after the first execution, the values for each loop iteration from one execution to another do not change. The Feedback Node behaves differently if you do not wire an initial value to the initializer terminal, shown as follows.

First Execution Second Execution
Iteration End Value Iteration End Value
0 1 0 5
1 2 1 6
2 3 2 7
3 4 3 8

In the previous block diagram, the initializer terminal uses 0, the default value for the data type, as the initial value in the first execution and does not reinitialize the Feedback Node in any subsequent executions.

Although you can separate the node and initializer terminal in loops and nested loops, you cannot move the initializer terminal outside the set of nested structures that contains the node. You also cannot separate the node from the initializer terminal when you create a subVI. If you attempt to create a subVI from a section of the block diagram that contains either the node or the initializer terminal, but not both, LabVIEW returns an error.

Replacing Shift Registers with a Feedback Node

Replace a shift register with a Feedback Node by right-clicking the shift register and selecting Replace with Feedback Node from the shortcut menu. Replace a Feedback Node with shift registers by right-clicking the Feedback Node and selecting Replace with Shift Register from the shortcut menu.

Default Data in Loops

Loops produce default data on the first iteration when the shift register is not initialized.

For Loops produce default data if you wire 0 or a negative number to the count terminal of the For Loop or if you wire an empty array to the For Loop as an input with auto-indexing enabled. The loop does not execute, and any output tunnel with auto-indexing disabled contains the default value for the tunnel data type. Use shift registers to transfer values through a loop regardless of whether the loop executes.


Resources


 

Your Feedback! poor Poor  |  Excellent excellent   Yes No
 Document Quality? 
 Answered Your Question? 
Add Comments 1 2 3 4 5 submit