.. _loops-ex1:

Ex. 1: For loop
---------------

In this example, you will learn how to use the :ref:`flow_control-loop` node to
loop over a range of values (from ``0`` to ``9``) and evaluate the function:

:math:`y = x^2`

First, add a :ref:`flow_control-loop` node to the sheet. Make the node large by
clicking and dragging the resize handle in the bottom right corner so we can fit
node inside. Create two ``Tunnel``
terminals on the left of the node and one on the right. Right-click the top-left
terminal and change it to an ``Indexed`` terminal. Do the same with the terminal
on the right. Your sheet should now look like this:

.. figure:: ./images/ex1_loop.png
   :align: center
   :width: 300

Next, add a ``math.Power`` node inside the :ref:`flow_control-loop` node.
Connect the top-left ``Tunnel`` terminal to the ``base`` terminal on the
``Power`` node and the bottom-left ``Tunnel`` terminal to the ``exponent`` terminal
of the ``Power`` node. Finally, connect the ``result`` of the ``Power`` node
to the right ``Tunnel`` node.


.. figure:: ./images/ex1_power.png
   :align: center
   :width: 300

Now that all the connections inside the loop are complete, add ``Range`` and
``Float`` nodes to the left of the :ref:`flow_control-loop` node. Connect the
``range`` terminal on the ``Range`` node to the top-left ``Tunnel`` terminal on
the :ref:`flow_control-loop` node. Connect the ``Float`` terminal to the
bottom-left ``Tunnel`` terminal on the :ref:`flow_control-loop` node. Change the
value of the ``Float`` node from ``0`` to ``2``.

.. figure:: ./images/ex1_range.png
   :align: center
   :width: 400

Finally, to show the results of the loop, add a ``Plot`` node to the right of
the :ref:`flow_control-loop` node. Connect the right ``Tunnel`` terminal on the
:ref:`flow_control-loop` node to the ``y`` terminal on the ``Plot`` node. Run
the sheet by pressing the |play| button.

.. figure:: ./images/ex1_complete.png
   :align: center
   :width: 600

.. |play| image:: ../../../nodeworks/images/play.svg