大象传媒

Determining the purpose of simple algorithms

When given an , there are a number of ways to determine what the purpose of the algorithm is. Sometimes it is clear as the algorithm is simple; however, at other times it is useful to 鈥榙ry run鈥 the algorithm to see what is taking place.

Dry running an algorithm means to assign the values to of an algorithm and to do any processing that takes place without translating it into code.

Trace tables

enable the variable values in an algorithm to be recorded as the algorithm is dry run. For example, using the times table algorithm below, a table could be created showing the value of the variables num and number as the program runs:

num 鈫 USERINPUT
FOR number 鈫 1 TO 10
  OUTPUT number * num
ENDFOR
NumNumberOutput
155
210
315
420
525
630
735
840
945
1050
Num1
Number5
Output5
Num2
Number
Output10
Num3
Number
Output15
Num4
Number
Output20
Num5
Number
Output25
Num6
Number
Output30
Num7
Number
Output35
Num8
Number
Output40
Num9
Number
Output45
Num10
Number
Output50

Visual inspection

Some algorithms follow a pattern that can be recognised. Many of these are referred to as and often follow a set pattern for searching for or sorting . Sometimes it is clear what this is just by looking at the . For example, the algorithm below follows a recognisable pattern for searching through each letter of a word and checking if the letter entered matches. This would be a useful decomposed part of a hangman game.

guess 鈫 USERINPUT
FOR i 鈫 0 TO LEN(word)
   IF word[i] = guess THEN
     OUTPUT 鈥渇ound鈥
     ENDIF
ENDFOR