PDE - Infinity Here We Come (Lesson)

Infinite Loops - When do we go to Infinity?

 

What is an infinite loop / iteration?  A loop that does not end, just goes on and on and on.  Like putting a selected group of music on shuffle and play, the music keeps playing until you stop it.

If you are asked to design an iteration / loop that does not end, make sure you clearly write down the obvious.  Do not use words that can be misconstrued.  

Example:   Take this correctly written code iteration and answer the questions below.

cnt = 5 

                   while cnt > 3

                       move 6 

                       cnt = cnt - 1

Following are questions to go with this loop example shown above.

1.  Describe how the while loop provided works.

The variable cnt is set to 5 prior to the loop running.  Evaluation of the while condition of truth yields 5 > 3 so the loop is entered, the object moves 6 and the cnt variable is reduced by 1 , cnt - 1, so cnt is now 4.  

2.  Trace of code showing the working loop values as they are changed.                  

 PDE - Here We Come Loop Trace.png

3.  How many times is the loop executed?

                 2 times

4.  How can you rewrite the code to make the code infinitely loop?  

      • In this code, the cnt = cnt - 1 is removed, and the cnt stays stuck on the value of 5, so 5 > 3 remains as the constant comparison.

                      cnt = 5 

                      while cnt > 3

                          move 6 

                      

      • In this code, the cnt = cnt - 1 is changed to cnt = cnt + 1, switching the operation sign from subtraction to addition.  The addition causes the cnt to increase each time the loop is executed, thus heading for infinity.  The while condition of truth is always tested as cnt > 3, but with cnt starting at 5 and adding 1 each time, cnt remains > 3, just larger with each iteration.

                      cnt = 5 

                      while cnt > 3

                          move 6 

                           cnt = cnt + 1

 

Let's answer the question:  When do we go to infinity? 

        Usually when the programmer

    • makes a mistake in not using the control variable of the loop (the first example in #4)
    • makes a mistake in using the control variable, usually sending the incrementation the wrong way (the second example in #4)

          If your program is running on and on, check your iterations.