Algorithms : Loops

Algorithms : Loops

Say that again.

Introduction

Flowchart iterationIn the previous sections we looked at the first two basic structure which are sequence and decisions. In this section we will add the final structure and look at how we make loops, also known as repetition or iteration.

We are interested in the ability to run a group of processes within our algorithm over and over a number of times.

There are three types of loops that we will look at :

  • Pre-test loops
  • Post-test loops
  • Stepped loops (For/Next)

In this section of the algorithms tutorial we will investigate two methods of algorithm description commonly used in software engineering :

  • Pseudocode - a text based method
  • Flowcharts - a graphical method

The two methods are comparable and have the same features. Anything you can represent in one, you can represent similarly in the other.

Pre-Test Loops

These are the most common loops that you will probably use. They are easy to conceptualise and to understand.

WHILE condition is true
    processes
ENDWHILE

while loop

Let's say we were to make a very simple guessing game. We set a variable to a random number than allow the user to keep guessing until they get it correct :

Simple Guessing Game

  1. BEGIN
  2.   Display "Guess the number between 1 and 100"
  3.   Set target to random number between 1 and 100
  4.   Get guess
  5.   WHILE guess != target
  6.     Display "That is not the number. Try again"
  7.     Get guess
  8.   ENDWHILE
  9. END

The nice thing about pre-test loops is that they can be executed zero times if the conditions dictate. In the above example, if the user guesses the number correctly on the first attempt then the loop will not need to run.

Priming reads

A Priming read is when we ask for a value or read a line from a file that is important in the condition of the loop prior to entering the loop.

In the above example you will notice that we have a line that is duplicated (lines 4 and 7). It may seem like there should be a better solution which allows for this line to appear only once in the algorithm. It is possible to remove the redundancy however we would then need an if statement in order to handle the possibility of the user guessing correctly on the first go. Here is an example :

Simple Guessing Game without duplicated Get

  1. BEGIN
  2.   Display "Guess the number between 1 and 100"
  3.   Set target to random number between 1 and 100
  4.   Set guess to -1
  5.   WHILE guess != target
  6.     Get guess
  7.     IF guess != target THEN
  8.       Display "That is not the number. Try again"
  9.     ENDIF
  10.   ENDWHILE
  11. END

On line 4 we set the value of guess to -1 so that the variable is known before we try to use it in the condition of the loop on line 5.

As you can see, we have removed the redundancy however the algorithm is more complex as a result. When we use the duplicated getting a value just before entering the loop we call this a priming read. We are priming the variable that is involved in the condition of the loop just before entering the loop. It is a common pattern that programmers use and you should become familiar with it as it is quite effective.

Post-Test Loops

Post-test loops behave in the opposite way to pre-test loops. Instead of having the condition at the top of the loop, the condition is at the end and instead of repeating while the condition is true, you repeat until the condition is true. These are not used as often as pre-test loops (and in fact, many programming languages such as Python don't even have them) but sometimes they allow for cleaner logic.

REPEAT
    processes
UNTIL condition is true

repeat loop

In the following example we will continue to ask the user for numbers until the total is over 100 :

Simple adding program

  1. BEGIN
  2.   Set total to 0
  3.   REPEAT
  4.     Get nextNumber
  5.     total = total + nextNumber
  6.   UNTIL total > 100
  7.   Display total
  8. END

With the WHILE loop is was possible to have the loop run zero times. With the REPEAT loop the loop must run at least once. This is important to understand when setting up your logic.

Converting between Pre-Test and Post-Test Loops

Despite the two types of loops having slightly different behaviour it is possible to represent the logic of an algorithm using one with equivalent logic using the other. To do so you just need to modify the logic in the condition slightly as follows.

Replace :

  • AND with OR and vice versa
  • > with <= and vice versa
  • >= with < and vice versa
  • == with != and vice versa

Here are some examples to illustrate. Rather than come up with scenarios, I have just used plain variables so that it is easy to follow. You may want to work through the steps by hand to verify that they are in fact equivalent.

Example 1

example 1 while

  1. BEGIN
  2.   Set var1 to 4
  3.   Set var2 to 8
  4.   WHILE var1 < 10 and var2 > 1
  5.     var1 = var1 + 1
  6.     var2 = var2 - 1
  7.   ENDWHILE
  8. END

Will perform the same as :

example 1 repeat

  1. BEGIN
  2.   Set var1 to 4
  3.   Set var2 to 8
  4.   REPEAT
  5.     var1 = var1 + 1
  6.     var2 = var2 - 1
  7.   UNTIL var1 >= 10 or var2 <= 1
  8. END

Example 2

example 2 while

  1. BEGIN
  2.   Set var1 to 4
  3.   Set var2 to 8
  4.   WHILE var1 < 10 or var2 > 1
  5.     var1 = var1 + 1
  6.     var2 = var2 - 1
  7.   ENDWHILE
  8. END

Will perform the same as :

example 2 repeat

  1. BEGIN
  2.   Set var1 to 4
  3.   Set var2 to 8
  4.   REPEAT
  5.     var1 = var1 + 1
  6.     var2 = var2 - 1
  7.   UNTIL var1 >= 10 and var2 <= 1
  8. END

Example 3

example 3 while

  1. BEGIN
  2.   Set var1 to 4
  3.   WHILE var1 <= 20
  4.     var1 = var1 + 1
  5.   ENDWHILE
  6. END

Will perform the same as :

example 3 repeat

  1. BEGIN
  2.   Set var1 to 4
  3.   REPEAT
  4.     var1 = var1 + 1
  5.   UNTIL var1 > 20
  6. END

Stepped Loops

With the prior two loops, they will repeat an unspecified amount of times until the right condition is met. Sometimes you want to run a set of processes a set amount of times. Whilst this may be done with the prior two loops, there is a final loop which makes it clearer and more direct what is going on.

FOR variable = start TO finish STEP increment
    processes
NEXT variable

for loop

Here is a simple example with printing 5 times tables :

5 Times Tables

  1. BEGIN
  2.   Display "5 Times Tables"
  3.   FOR counter = 1 TO 10 STEP 1
  4.     Set multiple to counter x 5
  5.     Display counter " : " multiple
  6.   NEXT counter
  7. END

Here is the same functionality but using a WHILE loop :

5 Times Tables using WHILE

  1. BEGIN
  2.   Display "5 Times Tables"
  3.   Set counter to 1
  4.   WHILE counter <= 10
  5.     Set multiple to counter x 5
  6.     Display counter " : " multiple
  7.     Increment counter by 1
  8.   ENDWHILE
  9. END

It's not excessively more complex but it is several lines more than the equivalient FOR loop.

Other examples

Here is a simple algorithm which will keep asking for numbers until a number divisible by 3 is entered. It will then print out the average of the numbers.

average of numbers flowchart

% means 'mod' or modulus which means give the remainder after performing a division.

Here is a simple algorithm which will print a triangle of asterisks ( * ) (triangle on its side like the end of an arrow):

Asterisk Triangle

  1. BEGIN
  2.   Get length
  3.   Get height
  4.   Set midway to integer of height / 2
  5.   Set counter to 1
  6.   WHILE counter < midway
  7.     Print counter number of "*"
  8.     Increment counter by 1
  9.   ENDWHILE
  10.   Decrement counter by 1
  11.   WHILE counter > 0
  12.     Print counter number of "*"
  13.     Decrement counter by 1
  14.   ENDWHILE
  15. END

Alternate a value (flip flop)

This algorithm will alternate a variable between two states every time an event occurs :

Alternate values

  1. BEGIN
  2.   Get trigger
  3.   Set action to False
  4.   WHILE True
  5.     IF trigger == SPACEBAR and action == False THEN
  6.       Set action to True
  7.     ELSEIF trigger == SPACEBAR and action == True THEN
  8.       Set action to False
  9.     ENDIF
  10.  
  11.     IF action == True THEN
  12.       
  13.     ELSE
  14.       
  15.     ENDIF
  16.  
  17.     Get trigger
  18.   ENDWHILE
  19. END

Summary

WHILE condition processes ENDWHILE
Pre-test loop
REPEAT processes UNTIL condition
Post-test loop.
FOR variable = value TO value STEP value processes NEXT variable
Stepped loop.

Most loops may be implemented via several of these.
Picking the right loop type will make the logic easier to understand.
Priming read
Reading a variable before entering the loop to set things up.