Difference between revisions of "W1152 While Loop"

From Coder Merlin
(5 intermediate revisions by the same user not shown)
Line 15: Line 15:
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.
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.
}}
}}
== While Loop ==
A '''while''' loop:
* Tests a condition
* If the condition is true, the statements within the body of the loop are executed, then the condition is re-evaluated
* If the condition is false, execution continues with the statements ''after'' the body of the loop


== Flowchart ==
== Flowchart ==
Line 24: Line 30:
{{ResponsiveImage|[[File:While Loop Assembly.png]]}}
{{ResponsiveImage|[[File: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''.
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''.
Carefully study the following assembly language example:
<syntaxhighlight lang="gas" highlight="8,15,29,37" line>
        .global _start
        .text
_start:
        # load the loop control variable
        mov    (loopControlVariable), %r8  # load %r8 from a variable
test:
        # we then test to see if the number is greater than 4
        cmp    $4, %r8                    # subtract 4 from the contents of register r8
        # evaluate test condition, jump conditionally (less-than or equal)
        jle      alternative
consequent:
        # write(1, messageConsequent, 11)
        mov    $1, %rax                  # system call 1 is write
        mov    $1, %rdi                  # file handle 1 is stdout
        mov    $messageConsequent, %rsi  # address of string to output
        mov    $11, %rdx                  # number of bytes
        syscall                            # invoke operating system to do the write
        # alter loop control variable, one step closer to termination
        dec    %r8
        # jump to test condition at beginning of loop
        jmp    test                      # jump unconditionally
alternative:
        # write(1, messageAlternative, 12)
        mov    $1, %rax                  # system call 1 is write
        mov    $1, %rdi                  # file handle 1 is stdout
        mov    $messageAlternative, %rsi  # address of string to output
        mov    $12, %rdx                  # number of bytes
        syscall                            # invoke operating system to do the write
afterAlternative:
        # exit(0)
        mov    $60, %rax                  # system call 60 is exit
        xor    %rdi, %rdi                # we want return code 0
        syscall                            # invoke operating system to exit
loopControlVariable:
        .quad    8
messageConsequent:
        .ascii  "Consequent\n"
messageAlternative:
        .ascii  "Alternative\n"
</syntaxhighlight>


{{Observe|Section 1|
{{Observe|Section 1|
# Why is the test executed prior to the loop?  
# Why is the test executed ''prior'' to the loop?  
# Compare this diagram to that of the conditional.  What are the similarities?  What are the differences?
# Compare this diagram to that of the conditional.  What are the similarities?  What are the differences?
# What is the purpose of the ''Jump'' instruction after the ''consequent''?
# What is the purpose of the ''Jump'' instruction after the ''consequent''?
}}
}}
== Swift ==
<syntaxhighlight lang="swift">
var x = 8                                                                                                                                                                                                                                                                                                                                     
while x > 4 {                                                                                                                                                                                                                                                                                                                                 
    print("consequent")                                                                                                                                                                                                                                                                                                                       
    x -= 1                                                                                                                                                                                                                                                                                                                                   
}                                                                                                                                                                                                                                                                                                                                             
print("alternative") 
</syntaxhighlight>


== Key Concepts ==
== Key Concepts ==
{{KeyConcepts|
* '''Loops''' are the general term for executing a defined segment of code zero or more times
** A loop generally requires a '''test condition''' which informs the CPU when the loop should exit
** A '''body''' which is the code that is repeated for each '''iteration''' (repetition) of the loop
** Each iteration of the loop ''must'' perform some action to move the loop closer to completion
* An '''infinite loop''' would theoretically execute forever, often because it lacks a test condition or the condition will never evaluate to the value required for the loop to exit
* In a '''while loop''':
** 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.
}}
== Exercises ==
== Exercises ==
{{W1152-Exercises}}
== References ==
== References ==

Revision as of 18:33, 12 January 2020

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.

While Loop[edit]

A while loop:

  • Tests a condition
  • If the condition is true, the statements within the body of the loop are executed, then the condition is re-evaluated
  • If the condition is false, execution continues with the statements after the body of the loop

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.

Carefully study the following assembly language example:

        .global _start

        .text
_start:
        # load the loop control variable
        mov     (loopControlVariable), %r8  # load %r8 from a variable

test:
        # we then test to see if the number is greater than 4
        cmp     $4, %r8                    # subtract 4 from the contents of register r8

        # evaluate test condition, jump conditionally (less-than or equal)
        jle      alternative

consequent:
        # write(1, messageConsequent, 11)
        mov     $1, %rax                   # system call 1 is write
        mov     $1, %rdi                   # file handle 1 is stdout
        mov     $messageConsequent, %rsi   # address of string to output
        mov     $11, %rdx                  # number of bytes
        syscall                            # invoke operating system to do the write

        # alter loop control variable, one step closer to termination
        dec     %r8

        # jump to test condition at beginning of loop
        jmp     test                       # jump unconditionally

alternative:
        # write(1, messageAlternative, 12)
        mov     $1, %rax                   # system call 1 is write
        mov     $1, %rdi                   # file handle 1 is stdout
        mov     $messageAlternative, %rsi  # address of string to output
        mov     $12, %rdx                  # number of bytes
        syscall                            # invoke operating system to do the write

afterAlternative:
        # exit(0)
        mov     $60, %rax                  # system call 60 is exit
        xor     %rdi, %rdi                 # we want return code 0
        syscall                            # invoke operating system to exit

loopControlVariable:
        .quad    8
messageConsequent:
        .ascii  "Consequent\n"
messageAlternative:
        .ascii  "Alternative\n"
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?

Swift[edit]

var x = 8                                                                                                                                                                                                                                                                                                                                      
while x > 4 {                                                                                                                                                                                                                                                                                                                                  
    print("consequent")                                                                                                                                                                                                                                                                                                                        
    x -= 1                                                                                                                                                                                                                                                                                                                                     
}                                                                                                                                                                                                                                                                                                                                              
print("alternative")

Key Concepts[edit]

Key ConceptsKeyConceptsIcon.png
  • Loops are the general term for executing a defined segment of code zero or more times
    • A loop generally requires a test condition which informs the CPU when the loop should exit
    • A body which is the code that is repeated for each iteration (repetition) of the loop
    • Each iteration of the loop must perform some action to move the loop closer to completion
  • An infinite loop would theoretically execute forever, often because it lacks a test condition or the condition will never evaluate to the value required for the loop to exit
  • In a while loop:
    • 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.

Exercises[edit]

Template:W1152-Exercises

References[edit]