Algorithms : Loops
Algorithms : Loops
Say that again.
Introduction
In 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
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
- BEGIN
- Display "Guess the number between 1 and 100"
- Set target to random number between 1 and 100
- Get guess
- WHILE guess != target
- Display "That is not the number. Try again"
- Get guess
- ENDWHILE
- 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
- BEGIN
- Display "Guess the number between 1 and 100"
- Set target to random number between 1 and 100
- Set guess to -1
- WHILE guess != target
- Get guess
- IF guess != target THEN
- Display "That is not the number. Try again"
- ENDIF
- ENDWHILE
- 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
In the following example we will continue to ask the user for numbers until the total is over 100 :
Simple adding program
- BEGIN
- Set total to 0
- REPEAT
- Get nextNumber
- total = total + nextNumber
- UNTIL total > 100
- Display total
- 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
- BEGIN
- Set var1 to 4
- Set var2 to 8
- WHILE var1 < 10 and var2 > 1
- var1 = var1 + 1
- var2 = var2 - 1
- ENDWHILE
- END
Will perform the same as :
example 1 repeat
- BEGIN
- Set var1 to 4
- Set var2 to 8
- REPEAT
- var1 = var1 + 1
- var2 = var2 - 1
- UNTIL var1 >= 10 or var2 <= 1
- END
Example 2
example 2 while
- BEGIN
- Set var1 to 4
- Set var2 to 8
- WHILE var1 < 10 or var2 > 1
- var1 = var1 + 1
- var2 = var2 - 1
- ENDWHILE
- END
Will perform the same as :
example 2 repeat
- BEGIN
- Set var1 to 4
- Set var2 to 8
- REPEAT
- var1 = var1 + 1
- var2 = var2 - 1
- UNTIL var1 >= 10 and var2 <= 1
- END
Example 3
example 3 while
- BEGIN
- Set var1 to 4
- WHILE var1 <= 20
- var1 = var1 + 1
- ENDWHILE
- END
Will perform the same as :
example 3 repeat
- BEGIN
- Set var1 to 4
- REPEAT
- var1 = var1 + 1
- UNTIL var1 > 20
- 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
Here is a simple example with printing 5 times tables :
5 Times Tables
- BEGIN
- Display "5 Times Tables"
- FOR counter = 1 TO 10 STEP 1
- Set multiple to counter x 5
- Display counter " : " multiple
- NEXT counter
- END
Here is the same functionality but using a WHILE loop :
5 Times Tables using WHILE
- BEGIN
- Display "5 Times Tables"
- Set counter to 1
- WHILE counter <= 10
- Set multiple to counter x 5
- Display counter " : " multiple
- Increment counter by 1
- ENDWHILE
- 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.
% 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
- BEGIN
- Get length
- Get height
- Set midway to integer of height / 2
- Set counter to 1
- WHILE counter < midway
- Print counter number of "*"
- Increment counter by 1
- ENDWHILE
- Decrement counter by 1
- WHILE counter > 0
- Print counter number of "*"
- Decrement counter by 1
- ENDWHILE
- END
Alternate a value (flip flop)
This algorithm will alternate a variable between two states every time an event occurs :
Alternate values
- BEGIN
- Get trigger
- Set action to False
- WHILE True
- IF trigger == SPACEBAR and action == False THEN
- Set action to True
- ELSEIF trigger == SPACEBAR and action == True THEN
- Set action to False
- ENDIF
- IF action == True THEN
- ELSE
- ENDIF
- Get trigger
- ENDWHILE
- END
Summary