Pseudocode Book
Pseudocode Book
Flowcharts were the first design tool to be widely used, but unfortunately they do not
very well reflect some of the concepts of structured programming. Pseudocode, on the
other hand, is a newer tool and has features that make it more reflective of the
structured concepts. Unfortunately, the narrative presentation is not as easy to
understand and follow.
PSEUDOCODE:
READ name, hourlyRate, hoursWorked, deductionRate
grossPay = hourlyRate * hoursWorked
deduction = grossPay * deductionRate
netPay = grossPay – deduction
WRITE name, grossPay, deduction, netPay
SEQUENCE: keep statements that are “stacked” in sequence all starting in the
same column.
SELECTION: indent the statements that fall inside the selection structure, but not
the keywords that form the selection
LOOPING: indent the statements that fall inside the loop, but not the keywords
that form the loop
EX: In the example above, employees whose grossPay is less than 100 do not
have any deduction.
TASK LIST:
Read name, hourly rate, hours worked, deduction rate
Compute gross, deduction, net pay
Is gross >= 100?
YES: calculate deduction
NO: no deduction
Write name, gross, deduction, net pay
PSEUDOCODE:
READ name, hourlyRate, hoursWorked
grossPay = hourlyRate * hoursWorked
IF grossPay >= 100
deduction = grossPay * deductionRate
ELSE
deduction = 0
ENDIF
netPay = grossPay – deduction
WRITE name, grossPay, deduction, netPay
yes no
amount
< 1000
interestRate = interestRate =
.06 .10
Some selections are of the “do it or don’t” (one sided) variety. For example:
IF average < 60
NULL
ELSE
DO GivePassingGrade
ENDIF
This could (and should) be rewritten to eliminate the NULL “yes” part. To do that, we
change the < to its opposite: >= as follows:
IF average >= 60
DO GivePassingGrade
ENDIF
NESTING IF STATEMENTS
What if we wanted to put a little menu up on the screen:
1. Solitaire
2. Doom
3. Monopoly
and have the user select which game to play. How would we activate the correct
game?
READ
READ gameNumber gameNumber
IF gameNumber = 1
DO Solitaire
ELSE
IF gameNumber = 2 yes no
gameNumber
DO Doom =1?
ELSE yes no
DO Monopoly gameNumber
=2?
ENDIF DO
ENDIF Solitaire
DO Doom DO
Monopoly
We must pay particular attention to where the IFs end. The nested IF must be
completely contained in either the IF or the ELSE part of the containing IF. Watch for
and line up the matching ENDIF.
LOOPING STRUCTURES
One of the most confusing things for students first seeing a flowchart is telling the loops
apart from the selections. This is because both use the diamond shape as their control
symbol. In pseudocode this confusion is eliminated. To mark our loops we will use
these pairs: WHILE / ENDWHILE REPEAT / UNTIL
Count = 0 count = 0
WHILE count < 10
ADD 1 to count
WRITE count
ENDWHILE
WRITE “The end”
Count no
< 10
yes
Notice that the connector and test at the
top of the loop in the flowchart become
Write the WHILE stmt in pseudocode. The
Add 1 to count “The end of the loop is marked by
end” ENDWHILE.
Sometimes it is desirable to put the steps that are inside the loop into a separate
module. Then the pseudocode might be this:
count = 0
Count = 0 REPEAT
ADD 1 to count
WRITE count
UNTIL count >= 10
WRITE “The end”
Add 1 to count Notice how the connector at the top of the loop
corresponds to the REPEAT keyword, while
the test at the bottom corresponds the the
UNTIL stmt. When the loop is over, control
Write goes to the stmt following the UNTIL.
count
no Count
>= 10
yes
Write
“The end”
STOP
ADVANTAGES AND DISADVANTAGES
Pseudocode Disadvantages
It’s not visual
There is no accepted standard, so it varies widely from company to company
Pseudocode Advantages
Can be done easily on a word processor
Easily modified
Implements structured concepts well
Flowchart Disadvantages
Hard to modify
Need special software (not so much now!)
Structured design elements not all implemented
Flowchart Advantages
Standardized: all pretty much agree on the symbols and their meaning
Visual (but this does bring some limitations)
The computer stores all program data into memory locations. It knows these location by
their addresses. It is perfectly able to understand code like:
READ 19087, 80976, 10943, 80764
but we would have a hard time with it. So we name our storage locations using words
that are descriptive to us. Every language has its own (different) set of rules about how
these names are formed. We will use a simple style:
The READ statement tells the computer to get a value from the input device (keyboard,
file, …) and store it in the names memory location.
When we need to compute a value in a program (like grossPay) we will use what is
called an assignment stmt.
variable = expression
CALCULATION SYMBOLS
We will often have to represent an expression like the one that computes grossPay. To
symbolize the arithmetic operators we use these symbols
grouping ( )
exponent ** or ^
multiply *
divide /
add +
subtract -
ORDER OF EXECUTION
( ) equations in parenthesis
Note: when operators of equal value are to be executed, the order of execution
is left to right.
Examples:
AREA = R2
SUM = A2 + B2
PERIM = 2(L + W)
2
A A A A D D
C C 2 C
BC B B BC B BC
SYMBOL IS OPPOSITE TO
> <=
< >=
= <>
OR: if any of the conditions are true, the whole expression is true
NOT: reverses the outcome of the expression; true becomes false, false becomes true.
Taking the sorting example; let’s sort an array using the Bubble sort technique. This sorting
algorithm could be implemented in all programming languages but let’s see the C implementation.
uint32 indx;
uint32 indx2;
int temp;
int temp2;
int flipped;
What’s your impression?
if (ub <= 1)
return; Is it easy to understand at once
this C implementation?
indx = 1;
do
{
flipped = 0;
for (indx2 = ub - 1; indx2 >= indx; --indx2)
{
temp = This[indx2];
temp2 = This[indx2 - 1];
if ((*fun_ptr)(temp2, temp) > 0) Bubble sort is mostly used in teaching.
{ However, its performance is slow and in
This[indx2 - 1] = temp;
This[indx2] = temp2; 2.44 the students will discover that there
flipped = 1; are better algorithms.
}
}
} while ((++indx < ub) && flipped);
}
Page 1 of 16
Here is some pseudo code for this algorithm.
What’s easier to understand,
Set n to number of records to be sorted
the implementation in C or
repeat
pseudo-code?
flag = false;
for counter = 1 to n-1 do
if key[counter] > key[counter+1] then
swap the records;
set flag = true;
end if
end do
n = n-1;
until flag = false or n=1
repeat
set a flag to False
for each pair of keys
if the keys are in the wrong order then
swap the keys
set the flag to True
end if
next pair
until flag is not set. This is easier than the programming language but is not
so precise. Hence the above pseudo code examples are
OR even as follows
more useful for implementing purposes. This one-line
Keep swapping items until array is in order version may raise questions such as “on what basis do I
swap the items?” Therefore, it is important to be precise
too.
The main part is that it is important to provide easy to read but precise instructions; this will keep
the design simple and unambiguous.
(a) Take a left, then take a right, go down the stairs, on your right enter the kitchen, pick a cup
and pour some hot water and add some hot chocolate….
OR
The above line of instruction depends on the reader, some prefer to (a) if not experienced while
others prefer (b) because it nails it to the point. It is pretty concise too.
Page 2 of 16
Let us take Example 1 and divide the algorithm implementation in stages and conquer.
repeat n times
sum = f1 + f2
f2 = f1
f1 = sum
print sum
end loop
Page 3 of 16
If all the above sections of pseudo code are put together we will get something looking like the
example below
This if – endif statement would come in before code line 7. Pseudo Code Example 1 is one of the
ways that pseudo code can be written. Below is another example where it exempts the declaration
of the variable and directly initialises them to a value. It is quite wordy than Pseudo Code Example 1.
Initialise n to fifty
Initialise sum to zero
Initialise f1 and f2 to zero
repeat n times
add f1 and f2, store this value in sum
assign f1’s current value to f2
assign sum’s current value to f1
end loop
These examples are just suggested ways of writing pseudo-code. There are various approaches that
you can use. I have included a number of links in Table 2 each having variations of pseudo-code
writing techniques with few examples. No strict rules are defined but just easy to read but precise.
Page 4 of 16
Let’s look at another example
2. Nested Function
Now let’s have an example of a nested function in other words where a function calls another
function.
Exercise: Create an array of size 10 and assign random values to each element of the array and print.
The random values are generated by another function which we do not implement but it is just
invoked to complete our need.
Points to note
There are two function calls random() and size(). size() gets the size of the initialised array
and randon() generates numbers randomly.
The process could be re-written in a wordier format and quite precise than the above example. See
Pseudo Code Example 4 for this.
Pseudo Code Example 4 is very concise description of the algorithm and most programmers know
how to implement it.
Page 5 of 16
Desk – Checking
Desk checking is a way of testing your algorithm; it can be also called as code walk through. There
are several ways of testing for example by showing it to peers or by implementing it into a
programming language and just executing the code step-by-step. But desk checking is faster and it
helps one to think like a compiler and a debugger.
The Desk Check Guide at the link below has a range of examples with desk checking.
http://ironbark.bendigo.latrobe.edu.au/subjects/PE/2005s1/other_resources/desk_check_guide.ht
ml . This guide creates a table of input, outputs and various variables against the code lines and
checks what happens to the variables at each line of code. But this seems to be time consuming
especially if the algorithm is complex. Desk checking checks the internal workings of an algorithm.
There is power point on the teaching on desk checking. Use this link
http://www.docstoc.com/docs/15885541/Desk-Checking.
There is no fixed way of desk checking but taking the Fibonacci example I have suggested a simpler
way to do it (simpler than the Desk Check Guide).
Code line 11 Code line 12 Code line 13 Code line 14 Code line 15
At loopcounter Sum (f1 + f2) f2 f1 Increment loop by 1
2 2 1 1 3
3 3 2 3 4
4 5 3 5 5
5 8 5 8 6
Page 6 of 16
Extra Information
There are few keywords that are common while writing pseudo-code.
Keywords :
Do While...EndDo;
Do Until...Enddo;
Case...EndCase;
If...Endif;
Call;
When;
Most authors use scope terminators (Start-end, If-endif, for-endfor, do-endo) for loops
and iteration.
Generate,Compute,Process, etc.
Words such as set, reset, increment, compute, calculate, add, sum, multiply, ...
Displaying :
o print, display, input, output, edit, test , etc. with careful indentation tend to
foster desirable pseudocode.
Expressions
Common Operators: =, +, -, *, /, (), <, <=, >, >=, [], %, ^. Sometimes add, sum, subtract, etc. are used
instead. But a + b is better and quick to understand. Such are language independent while some are
not such as % or mod. Thus, it is better to specifically mention modulo, e.g. a modulo B.
Page 7 of 16
Useful links
All these links cover all the AS expectations but one particular link does not cover all of them. Hence, I have listed all these in a table. So for further
information you can refer to the following links. These include various sites of pseudo-code writing tutorials/information and desk checking.
Table 2: Useful Links with extra information and various examples to practice
Page 8 of 16
We live and learn.
There are few exercises below. These exercises are of a mixed range such as achieved, merit and excellence. They aim to cover the advanced concepts from
computer science to ensure students gain an understanding of modular algorithmic structure design. These exercises can be taken further and
implemented as expected for AS 2.46
Exercise 1: String reverse - Design an algorithm that reverses a string and print it.
Page 9 of 16
Exercise 2: Replace every third element in the array with the value 10. Assume that an array filled with values is already provided. (Hint: Use example 3)
Sample Answer1
Achieved Uses indexed data structure- array,
for loopcounter = 2 to size of the array length – 1 includes data type, specifies variables
arr[loopcounter]= 10; Merit Modifies the content in the indexed
data-structure, has boundary cases
loopcounter = loopcounter + 3; Excellence ×
endfor
A better way of
writing for loop.
Sample Answer 2 OR Sample Answer 3
Set loopcounter to 0 for the array from 2 to size of the array length -1 by 3
for every third element in the array replace the existing value with 10
replace the existing value with 10 endfor
increment loopcounter by 3 ;
endfor
ASIDE: You can extend this exercise for example; consider there are duplicated values in the array. To delete duplicated values you will have to first sort the
array and then delete them. Moreover, you will have to decrease the size of the array. In addition you can also insert values at various places in the array.
Page 10 of 16
Achieved ×
Merit Modifies the contents of the indexed data structure
Excellence (If Sample Answer 3 is used then this level can be achieved
too). It calls a module to conduct the Caesar Cipher.
Exercise 3: Caesar Cipher- it is an encryption technique for sending secret messages. Let’s take the example of the alphabets.
You can have a look and experiment with various words at http://www.secretcodebreaker.com/caesar-cipher.html. This
Sample Answer
Alternatives for the output statement can be: Define code (parameters: c)
return c + 3 modulo 26
Sample Answer 2 Sample Answer 3
output k characters after c in the alphabets OR output code(c)
For some the Sample Answer1 is easier to understand while for others the alternatives spell out all that they need. Note: If Sample Answer 3 is used then it
satisfies the excellence expectation.
Page 11 of 16
Achieved ×
Merit ×
Excellence Calls modules, well-structured logical
decomposed task.
Exercise 4: Multiple modules
Print a line of stars and then for five times print an asterisk, multiple spaces and print an asterisk and then finally print again a line of stars.
ASIDE: To fulfil each of the condition of the exercise two separate functions have been defined - FullLine and a HollowLine. These have no parameters. We
could have compressed it all in one function as below.
print 5 asterisks
newline Which one is elegant, the one
repeat five times above or this one?
print *
print 3 spaces
print *
newline
print 5 asterisks
newline
The example above has modules that constitute a well-structured logical decomposition for the task.
There are more similar exercises, but these use parameters. Even though the AS does not expect to let’s practice with these.
Page 12 of 16
Achieved ×
Merit ×
Excellence Calls modules, well-structured logical
Exercise 5: Convert binary to Hexadecimal (relates to AS 2.44) decomposed task.
Sample Answer
ConvBintoHex (parameters: binarynumber)
Declare a string variable numbin Divides binary number in groups each containing 4
Read in value numbin to a value of binary numbers binary number and computes a value for each group
Call ConvBintoHex(arguments:numbin) and return the hexadecimal numbers
print numhex
Important to note: The word Call is significantly used when invoking another procedure or module.
The function contains a parameter and in the relevant box it shows how to write pseudo-code for functions with parameters. Note the difference when a
function with parameters is defined and when it is called. When the function is invoked it uses the notation ‘arguments’ but the notation used for the
function header is ‘parameters’. Some websites use: Call function name with parameter name, for example Call ConBintoHex with numbin.
Page 13 of 16
Achieved ×
Merit ×
Excellence Calls modules, well-structured logical
decomposed task.
Exercise 6: Tower of Hanoi
Before starting the exercise a video at this link http://www.youtube.com/watch?v=bPgv9D0lMfs&feature=related can be shown to the students.
Furthermore, http://www.youtube.com/watch?v=aGlt2G-DC8c can be shown to the students; this video shows the tower of Hanoi process in a slow
motion and with few disks.
While writing the pseudo-code for tower of Hanoi for a number of disks there are few considerations. The disks of different sizes are stacked in ascending
order of size; from the largest to the bottom to the smallest at the top. Stack the disks from tower one to tower three as shown in the figure below. Only
one disk may be moved at a time. No disk may be placed on top of a smaller disk at any time (even in the process of stacking). Let’s experiment with three
disks.
Sample Answer
Algorithm start
Move from Tower A to Tower C
Move from Tower A to Tower B
Move from Tower C to Tower B
Move from Tower A to Tower C
Move from Tower B to Tower A
Move from Tower B to Tower C
Move from Tower A to Tower C
Algorithm end
Page 14 of 16
The algorithm calls a module named move, this module moves the each disk one at a time. I have included a pseudo code found on a website to handle
indefinite number of disks.
Page 15 of 16
Let’s see if you can solve this.
Say, you ask a friend to go out and buy 1L of milk, and if there are eggs, to buy 10. So what does your friend buy in the end?i
It is precise, is it unambiguous?
MORAL: There is no one defined way of writing pseudo code but a pseudo-code should possess three elements: clarity, precision and concise.
i
10 Litres of milk
Page 16 of 16