W1152 While Loop

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Infinite loop BSOD

Prerequisites[edit]

General Loop[edit]

General Loop

Loops are the general term for executing a defined segment of code zero or more times, where the number of iterations is dependent upon test conditions within the loop.

In the case of a general loop, we can see that the three statements in the figure on the right will be repeated. However, without a test condition this loop would theoretically execute forever and is formally termed an infinite loop. To be useful, a test condition is required in order to inform the CPU when the loop should be exited. Thus, loops generally have two distinct parts:

  • A test condition which informs the CPU when the loop should exit
  • A body which is the code which is repeated for each iteration of the loop


CautionWarnIcon.png

Each iteration of the loop must perform some action, albeit slight, to move the loop closer to completion. If this does not occur, the loop would execute an infinite number of times.

Flowchart[edit]

A flowchart representing the above requirements follows:

   While Loop Flowchart.png

Assembly Language[edit]

Let's consider how the above construct is implemented in assembly language:

   While Loop Assembly.png

The condition, the Boolean test, is evaluated. If the test evaluates to false, a jump is executed to the alternative, otherwise execution continues with the consequent. At the end of the consequent, a jump is executed to the Boolean test.

ObserveObserveIcon.png
Observe, Ponder, and Journal: Section 1
  1. Why is the test executed prior to the loop?
  2. Compare this diagram to that of the conditional. What are the similarities? What are the differences?
  3. What is the purpose of the Jump instruction after the consequent?

Key Concepts[edit]

Exercises[edit]

References[edit]