0% found this document useful (0 votes)
3 views458 pages

Basic Programming Principles (2nd Edition)

The document is a textbook titled 'Basic Programming Principles' aimed at teaching fundamental problem-solving and programming concepts. It covers a range of topics including data hierarchy, variables, algorithms, control structures, and object-oriented programming, using pseudocode as a primary design method. The book is designed to equip readers with essential skills for programming and logical reasoning without delving into specific programming languages.

Uploaded by

jvdbstudio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views458 pages

Basic Programming Principles (2nd Edition)

The document is a textbook titled 'Basic Programming Principles' aimed at teaching fundamental problem-solving and programming concepts. It covers a range of topics including data hierarchy, variables, algorithms, control structures, and object-oriented programming, using pseudocode as a primary design method. The book is designed to equip readers with essential skills for programming and logical reasoning without delving into specific programming languages.

Uploaded by

jvdbstudio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 458

Basic Programming

Principles
Second Edition

CM Pretorius

HG Erasmus
Pearson Holdings Southern Africa (Pty) Ltd.

Forest Drive, Pinelands, Cape Town

www.pearsoned.co.za

Copyright © Pearson Education South Africa (Pty) Ltd


2012

All rights reserved. No part of this publication may be


reproduced, stored in a retrieval system, or transmitted
in any form or by any means, electronic, mechanical,
photocopying, recording or otherwise without the prior
written permission of the copyright holder.

First published 2012

Print ISBN: 9781775786030

ePub ISBN: 9781775955580

Publisher: Juanita Pratt

Managing editor: Amelia van Reenen

Editor: Rachel Bey-Miller

Proofreader: Careena Koch


Indexer: Ellen du Toit

Book design: Christopher Davis

Typesetting and DTP work: Lizette van Greunen

Cover design: Flame Design

Cover artwork: Corbis

Every effort has been made to trace copyright holders.


The publishers apologise for any errors or omissions
and invite copyright holders to contact us if any have
occurred, so that they may be credited.
Preface
In the world of information technology, a thorough
knowledge and understanding of problem-solving and
basic programming principles are vital necessities.

The programming language used to solve the problem


does not usually matter to the end user. However, the
information needs to be reliable, user friendly and
correct in order to assist the end user in the decision-
making process. Therefore, the process of problem
solving is imperative.

This book focuses on the basic principles of problem


solving. Various problems have been supplied and the
subsequent steps to develop solutions have been
provided and discussed in detail. The authors followed
a step-wise approach to solving problems, including the
following:

identifying appropriate input and output variables,


algorithm design, as supplied in the IPO chart,
selection of appropriate data types for variables,
and
detailed algorithm in pseudocode.
The primary purpose in the development of this book
was to provide readers with exposure to elementary
problem-solving techniques.

This text book is suitable for teaching programming


concepts and logical constructs without referring to
program code, and it includes many design exercises.
Once you have grasped the concepts of problem
solving, you should be able to apply them to the syntax
of any programming language such as VB.NET, C++,
and Delphi.

The primary design method used in the text book is that


of pseudocode. Alternative methods are discussed in
Appendix A , where a clear example of each method
is provided. Lecturers may decide to include these
alternative methods as part of their lesson planning. A
student who is able to develop proper pseudocode
should experience no difficulty in drawing a flowchart or
a Nassi-Shneiderman diagram.
Acknowledgements
The authors would like to thank all the people who
helped to make this book a reality. Without your
support, this publication would not have been possible:

Juanita Pratt and Rachel Bey-Miller of Pearson:


thanks for your encouragement and assistance.
Bertie Buitendag: thanks for all your ideas and input.
To our families: thanks for your support, love and
understanding.

We would like to dedicate this book to all our students,


ex-students and students to come. We hope that this
book will equip you to successfully undertake the
challenges of computer programming and that it will
kindle your enthusiasm for problem solving and
programming. We also hope that it will motivate you to
work hard to achieve your goals to become a developer
in the IT field.

May you benefit from this book and always remember


that control structures form the foundation of most
program solutions. Enjoy your exciting journey exploring
ways of solving problems by making use of the basic
control structures!
Contents
Chapter 1 General concepts and arithmetic 1
Introduction 1

1 Data hierarchy 2
1.1 Character 2

1.2 Field 3

1.3 Record 3

1.4 File 3

1.5 Table 3

1.6 Database 3

1.7 Data warehouse 4

2 Variables 4
2.1 Naming a variable 4

2.2 Types of variables 5

2.3 The value of a variable 7

3 Constants 8

4 Using variables in expressions and


assignments 8
5 Arithmetic expressions 9
5.1 Key words used in arithmetic expressions
9

5.2 Arithmetic expressions and equations 10

5.3 Arithmetic operators 11

5.4 Setting up arithmetic equations 13

5.5 Examples using variables and constants


14

Chapter 2 Understanding a problem and using a


computer to solve it 18
Introduction 18

1 Problem solving 18

2 Understanding the problem 19

3 Data processing 23

4 The problem-solving approach 24


4.1 Analyse the problem 24

4.2 Identify alternative ways to solve the


problem 25

4.3 Select the most effective way to solve the


problem 25

4.4 List all the steps 26

4.5 Evaluate the algorithm for accuracy 26


4.6 Pseudocode 26

4.7 What does pseudocode entail? 28

4.8 Writing an algorithm 29

Chapter 3 Write algorithms in sequential steps 31


Introduction 31

1 Program planning 31

2 Testing the logic of an algorithm 36

3 Calculating the outcome of an algorithm 46

Chapter 4 The selection control structure: Part 1 52


Introduction 52

1 Relational operations 53

2 Logical operations 54

3 The simple If statement 57


3.1 Testing a program that has an If
statement 59

3.2 Examples of simple If statements 62

4 The If-then-else statement 66


4.1 Examples of If-then-else statements 67

5 Compound If statements 71

6 Data validation 77
Chapter 5 The selection control structure: Part 2 80
Introduction 80

1 Nested If statements 81
1.1 Nested If statements in programs 87

2 The Select Case structure 98

Chapter 6 Iteration using a fixed count loop 110


Introduction 110

1 The For-next loop 110

2 Nested For statements 128

Chapter 7 Iteration using the Do loop 133


Introduction 133

1 The Do loop 133


1.1 Pre-test loop (Do-while statement) 133

1.2 Post-test loop (Do-loop-until statement)


135

1.3 Terminating execution of a loop 135

1.4 Examples of Do-while loops 136

1.5 Examples of Do-until loops 142

2. Examples of flowcharts for pre-test and post-


test loops 144

Chapter 8 Arrays 153


Introduction 153

1 Properties of arrays 154


1.1 Advantages of using a one-dimensional
array 156

2 Parallel (paired) arrays 169

3 Two-dimensional arrays 176

4 Sorting arrays 176


4.1 The bubble sort method 177

4.2 The selection sort method 177

Chapter 9 Function procedures and subprocedures


181
Introduction 181

1 Modules and modularisation 182

2 Hierarchy charts 182

3 Parameters 183
3.1 Value parameters 183

3.2 Reference parameters 183

4 Function procedures 184


4.1 The function call 184

4.2 The function 185

4.3 Calling a function and using a function


187
5 Subprocedures 193
5.1 The subprocedure call 193

5.2 The subprocedure 193

5.3 Calling an independent subprocedure and


using a subprocedure 194

5.4 Functions and subprocedures without


parameters 199

Chapter 10 Sequential text files 205


Introduction 205

1 Input and output files 206

2 Opening a sequential access file 206

3 Closing a sequential access file 207

4 Reading information from a sequential access


file 208

5 Writing information to a sequential access file


212

6 Reading from and writing to the same


sequential file 214

Chapter 11 Introduction to object-oriented


programming 218
Introduction 218

1 Concepts of object orientation 219


1.1 Objects 219

1.2 Properties 220

1.3 Operations 221

1.4 Classes 222

2 Encapsulation and information hiding 222

3 Design notations 224

4 Relationships between classes 224


4.1 Association 225

4.2 Aggregation 225

4.3 Inheritance 226

5 More concepts 227

6 Designing an object-oriented solution 228

Appendix A Tools for planning programs 229


Introduction 229

1 Pseudocode 229

2 Flowcharts 230

3 Nassi-Shneiderman diagrams 233

Symbols used to construct a Nassi-Shneiderman


diagram 234

Appendix B Error handling and debugging


techniques 236
Introduction 236

1 Types of errors 236


1.1 Syntax errors 236

1.2 Logical errors 237

1.3 Data errors 237

2 Trace tables 237

Glossary 241

Bibliography 244
Chapter 1 General
concepts and arithmetic

Introduction
Throughout our lives, we’re confronted
with problems we need to solve – for
instance, fixing a plug at home, taking
action to increase profits at work and
even trying to buy everything we need
within our budget when we go
shopping. Sometimes we solve a
problem without consciously going
through a formal process. We simply
execute a number of steps to come to
the solution.

In this book, we’ll be solving problems


using a computer. Although we will not
write the code in a programming
language or execute it on a computer,
we will be looking at algorithms to plan
the logic of the computer programs.
These problems will be more in the
domain of Mathematics and could be
very challenging, requiring careful
planning. However, we encourage you
to see all problems as opportunities
and to try various solutions until you
find one that solves the problem in the
most efficient, effective and
economical way.

The first aspect of a computer you


need to understand is that a computer
is just a dumb machine that can do
only what we tell it to do! So the
person (programmer) must first work
out the steps to solve a problem and
then use a compiler to translate the
steps into a computer programming
language that the ‘dumb machine’ can
understand. The programmer then
executes the program (the
instructions), and the computer
produces the solution.

Before we can start solving problems


or teach you steps/guidelines to follow
when planning the solution, you need
to understand and know some basic,
general concepts.

Outcomes
When you have studied this chapter, you should be able
to:
understand and know the hierarchy of data
structures,
understand what a variable is,
distinguish between data types,
distinguish between a variable and a constant,
write an assignment statement,
understand basic arithmetic operations,
use all arithmetic operators, and
set up and evaluate expressions and
equations using variables, constants,
operators and the hierarchy of operations.

1 Data hierarchy
Data is a collection of facts, such as values,
measurements, or readings. Data can be in the form of
numbers, words, measurements, observations or even
descriptions of things and events.
Data can be stored in the memory of the computer on a
temporary basis. However, it can also be stored more
permanently in various data structures for later use.
These data structures can be represented in a
hierarchy, from the smaller structures to the larger data
structures that are formed by a number of smaller
related structures.

Data hierarchy refers to the systematic organisation of


data from the smallest unit to the largest, as follows:

Table 1: The data hierarchy


Data warehouse Largest

Database ⇑

File and table ⇑

Record ⇑

Field ⇑

Character Smallest

1.1 Character
A character can be a single number, letter or special
character. Any one stroke that can be typed on a
keyboard is a character. Examples are 4, A, % and m.
1.2 Field
A field consists of a number of characters, such as a
number of persons (120) or a name (John). A field is
also known as a data item. The data types of fields are
discussed in section 2.2.

1.3 Record
Records normally group related fields together, such as
a student record, which could contain a student number,
the student’s name and surname and the course that
the student has enrolled for. Another example is an item
in a shop – the record could contain the item number,
description and price.

1.4 File
A file is a collection of related records such as an
employees file that contains records of all the
employees employed by a specific company. This file
may be used to process monthly salaries, print salary
reports and produce summaries. The records in the file
are organised and stored in a specific way, for
instance, sequentially one after the other.
1.5 Table
A table is a structure made up of rows and columns.
Each row represents the data of one entity regarding a
specific topic, e.g. data about one item in a shop, and
each column contains a category of data. For instance,
in an Employees table, one employee’s row would
contain the same categories of data, such as surname
and first name, as the other employees’ rows. However,
the data or values in each row would be different.

Table 2: A sample table


EmployeeID Surname First Job title Pay Fulltime?
Name Grade

DGS021 Bavuma Charles Foreman 7 True

DGS022 September Jontie Carpenter 5 True

DGS023 Tanda Goodwill Carpenter 5 False

1.6 Database
A database consists of a number of related files or
tables. This organisation depends on the processing
methods that need to be applied. For example, a
database could consist of three tables – one containing
students’ subjects and results, one containing students’
personal details, and a third containing details about the
students’ lecturers.

Depending on how a company processes data, they


may opt to use files, or tables and databases, or a
combination of these.

1.7 Data warehouse


A data warehouse is the largest structure used to
collect and store data for processing, analysis and
reporting. It may consist of several databases.

2 Variables
Programmers use the term ‘variable’ to refer to a
position or location in the memory of the computer
where a value can be stored. Initially, the variable need
not contain a value. The word variable indicates that the
value of the variable may vary as needed, or as
processing is done. You can visualise a variable as a
box in memory that contains one and only one specific
value at a given time.
2.1 Naming a variable
Every variable is given a descriptive name. There is no
need for the programmer to know the exact position
(address) of the variable, because the compiler will link
the given name of the variable to the actual address in
memory. When solving a problem, only one name is
given to a variable and this exact name is used all the
time. Although we are not writing the computer program
as yet and are still busy with the planning, we should
start to adhere to programming rules regarding the
choice of variable names.

When choosing a name for a variable, the programmer


must adhere to certain rules. These rules may differ
between programming languages, but for the purpose
of this book the following apply:

1. The name must be unique. While solving a


problem, two variables may not have the same
name.
2. The name must be descriptive – for instance, a
student’s grade could be called grade, whereas
the mark the student gets could be called mark.
3. The name may not contain spaces, but more than
one word can be joined to form a name. For
instance, the number of pages in a book could be
called bookPages and the price of an item could
be called itemPrice. The underscore character
can also be used to join words in a variable
name.
4. A name can contain letters and numbers, such as
department23, but cannot contain only numbers.
5. A variable name must start with a letter; it cannot
start with a number.
6. A variable name may not contain special
characters, such as &, # and @.
7. A variable name should be as short as possible,
while remaining descriptive.

2.1.1 How to name a variable


The convention is to use only lower-case letters in the
name of a variable, except where two or more words
are joined. In such cases, all the following words start
with an upper-case letter, which is known as camel
casing.

Table 3: Examples of variable names


Description Name

Name of employee empName

Price of car carPrice

Author of book author

Quantity in stock quantity


Age of student stAge

Total number of sales totNumSales

Questions
Do the following variable names comply with the rules?
If not, give a reason.

5thGrade
member of club
abc
5472
theAddressOfTheCompanyInTshwane
grade&mark

2.2 Types of variables


The following data types are applicable when variables
are classified.

2.2.1 Numeric variables

Integers
An integer variable contains a whole number that has
no fractional or decimal part. The number can be
positive, negative or zero. Examples of integers are the
number of students or the quantity of items in stock.
Integer variables are typically used for items that
cannot be split.

Examples: 15, –2334, 9728

Real numbers
A real number variable contains a positive or negative
number with a decimal part. Examples of real numbers
are the length of a window in metres or centimetres, or
an amount of money in Rands and cents.

Examples: 12.47, –987.123, 17.00

2.2.2 Non-numeric variables

Character
A character variable contains a single letter, number or
special character, such as $, % or @. The value of a
character variable is always enclosed in quotes.

Examples: “A”, “G”, “*”, “8”

Note that the character “8”, which is declared as a


character, is not regarded as numeric and may not be
used in calculations. When declared as a character, it
can be used as a code – for instance, the group
number is “8”.

String
A string variable consists of two or more characters
and must also be enclosed in quotes.

Examples: “32 Long Street” or a message, such as


“The name is found.”

Boolean
A Boolean value can only contain a true or false value.
In an everyday life situation a Boolean value can be
compared with a light switch, which is either on or off.
In a computer language, a true value is represented by
a non-zero value, whereas a false value is represented
by zero.

A Boolean variable is used to test if a specific condition


is true or false, and is also called a logical variable.

Examples: Is the person a club member? Did the


student pass an exam? True or false?

2.3 The value of a variable


A variable need not contain an initial value, but a value
can be assigned to a variable according to its data type
– for instance, the variable called costPrice may contain
a numeric real value. A value can also be assigned to a
variable while the statements in the algorithm are being
processed.

An illustration of this is the scoreboard for a football


match displaying the scores of the two teams. A team
has only one score at any given time. For example, at
the beginning the score will be zero, but after the first
goal it will be one. At no time may the scoreboard
contain two scores for one team.

Before the football match between Bafana Bafana and


Brazil, the scoreboard would be:

The same rule applies to a variable. When the value of


the variable changes, the previous value of the variable
is replaced by a new value. Once it’s been replaced, it
isn’t possible to retain the previous value in the same
variable.
Study the following table to understand all the aspects
of a variable.

Table 4: Examples of variable names, types and


values
Description Variable Variable Possible
name type value

Name of student stName String “John Smart”

Number of noBooks Integer 234


books

Price of item price Real number 78.56

Student? (Y/N) student Boolean true (or 1)

Code (A – C) code Character “B”

Exercises
Complete the following table:

Description Variable Variable Possible


name type value

Colour of dress

Height of person in
metres

Adult?
Age in years

Salary in R/c

Title of book

Player in match?

Class code (K, L or M)

Name of lecturer

Number of computers

3 Constants
All the rules of variables apply to constants as well,
except that constants have a fixed value that cannot
change throughout the entire program. Constants are
used in cases where we know that the value will never
vary during the execution of the program. A constant
may be any data type.

Examples:
There are always 24 hours in a day.

The value of π is always 3.14159.


A message or legend to be printed is “The name of the
student is”.

4 Using variables in
expressions and
assignments
The assignment symbol (=) is used to assign an initial
value or an expression to a variable.

Syntax: Variablename = Value

or

Variablename = Expression

Example: totalNumStudents = 20

totalNumStudents = numMales + numFemales

The first example, totalNumStudents = 20, means that


the value of a variable that contains the total number of
students is equal to 20. The second example, however,
indicates that the total number of students is equal to
the number of male students plus the number of female
students. NumMales and numFemales are both names
of variables.
5 Arithmetic expressions
The majority of computer programs contain arithmetic,
so it’s important to study how arithmetic is used to solve
problems using a computer. Arithmetic may be needed
to calculate the average marks of students, an amount
due on an invoice or the net salary of an employee
based on his or her gross salary.

5.1 Key words used in


arithmetic expressions
There are a number of key words that can be used in
problem statements containing mathematical
operations.

Addition

Key Examples
words

Increase Increase the total by 12.


by

More than Johan earns R50 more than Jack.

Combined Sam and Sally’s combined points are 129.


Together Together, Thabu and Jabu worked for 18 hours.

Total of Calculate the total of the first and the second sets of
quantities.

Sum What is the sum of the prices of 3 items?

Added to The 4th test mark must be added to the final mark.

Subtraction

Key words Examples

Decrease The final mark must be decreased by 10%.


by

Minus The amount minus the discount is the net amount.

Less than Pete earns R20 less than Simon.

Difference The difference between my height and your height is 5


cm.

Subtract Subtract 15 from the accumulated points.


from

Between The difference between Thandi’s mark and Rose’s mark


is 10.

Fewer than Goodman has worked five hours fewer than Samuel.

Multiplication

Key Examples
words

Of A quarter of 100 is 25.

Times The final mark is equal to the mark times 1.5.

Multiplied The wage is the hourly rate multiplied by the number of


by hours worked.

Product of Calculate the product of the number of items and the


price per item.

By a The total number must be increased by a factor of 12%.


factor of

Division

Key Examples
words

Per Calculate the kilometres travelled per litre of fuel.

Out of 15 out of 60 is 25%.

Ratio If the ratio of girls to boys is 2:3 and there are 25 children,
how many girls are there?

Divide Divide the number of minutes by 60 to get the number of


by hours

Quotient The quotient of 80 and 8 is 10.


of

Percent 50 percent of 250 ml is 125 ml.


Equals

Key Examples
words

Is/are The sum of 20 and 12 is 32.

Was/were The difference between my age and my grandmother’s


age was 60 years.

Will be The total of four numbers will be 300.

Give The prices of items bought give a total of R450.

Yields The calculation yields an answer of 36.

Sold for The final amount four items were sold for is R84.

Replaced After an increase of 10% the new calculated amount can


by be replaced by the sales amount.

5.2 Arithmetic expressions


and equationsexpressions
Equations are frequently used in arithmetic calculations,
for example:

answer = 4 + 7
The calculation to the right of the equal sign is done
first, then the result is assigned to the variable on the
left of the equal sign, which is ‘answer’ in this case. So
after the statement is executed, the variable called
answer will contain a value of 11.

The equals sign (=) has two meanings:

1. It can be used to assign a value to a variable. In


these two examples, both variables are integer.
total = 0
noOfStudents = 50
2. It can be used to replace the value of a variable.
In these two examples, all 3 variables are
numeric variables.
result = number * 2
sum = sum + points

The last example, sum = sum + points, will add the


value of points to the value of sum to produce a new
value for sum. The previous value of sum is increased
by the value of the variable points.

If sum has a value of 200 and points has a value of 27,


the right-hand side of the equation will be 200 + 27 and
the new value of sum will be 227. The previous value of
sum, which was 200, is now replaced by the new value,
which is 227.
5.3 Arithmetic operators
An operator is a symbol used within an expression or
equation that tells the computer how to process the
data. This symbol joins the operands to be processed –
for instance, in the calculation 3 * 6, 3 and 6 are
operands and * is the operator.

The following operators are used to perform arithmetic


operations:

Table 5: Arithmetic operators and the rules of


precedence
Operator Description Example Result Precedence

^ Exponentiation 2 ^4 16 1
(to the power of)

- Negation -TRUE FALSE 2


- -6 +6

*, / Multiplication and 5*7 35 3


division 72 / 8 9

\ Integer division 37 \ 5 7 4

mod Modulus 37 mod 2 5


arithmetic (integer 5
remainder part of
calculation)

+,- Addition and 4+7 11 6


subtraction 14 - 5 9

Integer division can only be done when dividing an


integer value by another integer value because it
discards (drops) the decimal part and doesn’t round the
answer. Example: 49 \ 10 = 4

Modulus arithmetic is done when the user only wants to


know what the value of the remainder is when dividing.
Example: 49 mod 10 = 9

The order of precedence in execution is important.


When an expression is executed, it is always done:

from left to right and


the operator with the highest order of precedence is
done before the others.

Note that when operators with the same precedence


occur in one expression, they will be executed from left
to right.

Study this example:

5−3^2\8+17 mod 3*2


To find the answer to this expression, we need to
determine which operator to execute first. The answers
in the steps that follow have been underlined.
Step 1: The exponentiation (3^2=9) is done first:
5−9¯\8+17 mod 3*2
Step 2: Multiplication and division are done from
left to right (3*2=6):
5−9\8+17 mod 6¯
Step 3: Integer division (9\8=1) is done next:
5−1¯+17 mod 6
Step 4: Modulus arithmetic (17 mod 6=5) is done
before addition or subtraction:
5−1+5¯
Step 5: Lastly, addition and subtraction are done
from left to right, so subtraction is done first
because the minus is to the left of the plus:
4¯+59¯

Parentheses (or brackets) are used to change the


order of execution. Calculations in parentheses have a
higher priority than any of the operators. However, the
operators inside the parentheses are executed
according to the same order of precedence.

Example: Calculate the value of the variable k where k


= a * b ^ (14 – c) mod 4 + 3 \ a, and where a, b and c
are integer variables with the following values:

a=3, b=5, c=11


Substitute the values of the variables before calculating:

k=3*5^(14−11)mod4+3\3=3*5^3¯ mod 4+3\3=3*125¯ mod 4+3\3=


+1=4¯
Note that (14 - 11) is executed before the other
operations because it’s in parentheses.

5.4 Setting up arithmetic


equations
An arithmetic equation is also called an assignment
statement in which variables and/or constants are
assigned to a variable on the left-hand side of an
equation. For example, a = b + c, where a must be a
numeric variable that will contain the result, and b and c
must also have numerical values, but may be constants
or variables.

A computer cannot understand mathematical equations


in the format that we usually write them. We therefore
need to translate the equation into a format the
computer can understand. Variables and/or constants
on the right-hand side of an equation are always
separated by operands. When writing an arithmetic
equation, the mathematical rules, as given in Table 5,
must be followed. An equation contains only one
variable to the left of the equation to store the result.

The following equation contains the variables X, A, B, C


and D:
X=A3−2B+2(C+D)2

The equation can now be written in computer-related


format, as follows:

X=A^3−2*B+(2*(C+D))/2

Note how the brackets are used to execute the


statements in the correct order.

Example:
Rewrite the following mathematical equation in
computer-related format as an assignment statement to
obtain the value of A:

3A = 2 (C – D )

Divide both sides of the equation by 3 and remember to


use brackets on the right-hand side.

A = (2 * (C – D)) / 3

Exercises
Rewrite the following equations in computer-related
format to determine the value of X, where A, B, C, D, E
and X are numeric variables:

4
1. X = AB + C4
2. X=C−DE+5−5D
3. X = 17BC - B(E-A)

5.5 Examples using


variables and constants
The following examples illustrate what you’ve just learnt.
In each of the examples, the arithmetic equation to
solve the problem is given after the variables and
constants have been planned. Note that meaningful
names were chosen for variables and constants.

Example 1
Kevin works eight hours per day at a pay rate of R11
per hour. He has to pay R12 taxi fare per day. How
much money will he take home after a five-day work
week?

Variables (integer): money

Constants hours = 8
(integers):

payRate = 11

transport = 12
noDays = 5

Equation: money = (hours * payRate – transport) *


noDays

The constants already contain values because these


values are fixed, but the amount earned, called money,
must still be calculated so doesn’t have an initial value.

Note that we don’t include the units (the Rand sign R) in


any calculation.

This also applies to other units such as metres,


centimetres, grams, kilograms and so on.

Example 2
Thandi has 257 items and wants to pack them in
packets of 14 each. How many full packets will she
have?

Variables (integer): fullPackets

Constant (integers): items = 257

noInPacket = 14

Equation: fullPackets = items \ noInPacket


To calculate how many will be left, you use the
equation:

numLeft = items mod noInPacket

Example 3
Joseph earns R5.75 per hour. He works eight hours per
day, but has to spend R3.60 on bus fare each day.
Determine his net income per day.

Variable (real number): netIncome

Constants (real numbers): tariff = 5.75

busFare = 3.6

noHours = 8

Equation: netIncome = tariff * noHours – busFare

Example 4
Bonita bought a number of items at R15.85 each. She
received a discount of 7.5%. Calculate the amount she
has to pay.

Variables (integer): noOfItems firstAmount, amountDue


(real numbers):
Constants (real numbers): discount = 7.5 priceOfItem = 15.85

The tilde character ( ∼) is used in the following answer


to indicate comments. These comments are not part of
the answer; they simply explain various aspects.

Possible equations
∼Assume noOfItems contains a value

firstAmount = noOfItems * priceOfItem

amountDue = firstAmount – (firstAmount * discount /


100)

∼The last statement could have been replaced by

amountDue = firstAmount * 0.925

∼The two arithmetic statements could have been


replaced by

amountDue = noOfItems * priceOfItem * 0.925

Exercises

Question 1
Complete the following table:
Description Variable Variable Possible
name type value

Number of pencils

Average height of person in


metres

Symbol (A, G, R or T)

Employed?

Weight of bean in mg

Price of bread

Gender (M/F)

Notice on door

Number on door

Able to swim?

Question 2
Choose suitable variable names for each of the
following and assign values where provided:

2.1. The number of marbles in a container.


2.2. The amount of money to pay
2.3. Are you registered?
2.4. Height of girl is 1.75 metres.
2.5. Name of person.
2.6. Code of item is K
2.7. Description of dog is Dachshund.
2.8. Number of smarties in a box

Choose suitable names for the following constants and


assign the correct values:

2.9. Seven days in a week


2.10. A notice contains the words “No Entry”
2.11. Value added tax at 14%

Question 3
Rewrite in computer-related format, then calculate the
value of x in each of the following equations:

3.1 x = a – bc 2 where a = 84, b = 3, c = 4

3.2 x = k mod 5 + m \ n – 3n where k = 34, m = 33, n = 7

3.3 x = a(bc + 4) – c + a mod b/a where a = 2, b = 10, c = 12

Question 4
Calculate the value of x in each of the following
statements:
4.1. x = g – 5 + 14 mod h ^ 2, where g = 12 and
h=1
4.2. x = 27 * y \ 4 / 2 – z + 2, where y = 24 and z
=4
4.3. x = a / (b + 2 ^ 2) – 12 + c mod b – 2, where
a = 96, b = 2, c = 98.
4.4. x = (y – 2 * z) + y / 6 * w \ 2, where w = 10,
y = 12, z = 2.
4.5. x = 35 mod y – ( z * w + y / 3 ) + y * w,
where w = 5, y = 24, z = 3

Question 5
Declare the necessary variables and constants and
write arithmetic expressions to solve the problems in
each of the following examples. Remember to choose
valid and meaningful variable names.

5.1. Sandra bought a number of pairs of socks at


R3.50 per pair. What is the amount due?
5.2. Vusi wrote two tests and obtained marks in
percentages for the tests.
Calculate her average mark.
5.3. Jimmy has some marbles and wants to give
each of four children an equal number. How many
will each child receive?
5.4. Solly bought a number of items and the
amount due is R245.60. He receives a discount
of 5%. Calculate the new amount due.
5.5. Determine the price to copy a set of notes
when the price for copying the cover page is
R1.50 and the price to copy the inner pages is 45
cents per double-sided page.
5.6. Nancy bought a number of items for R5.60
each. She receives a discount of 5% on the
amount due. Add 14% sales tax and then
calculate the amount due.
5.7. Tony scores points in two competitions – the
first competition is for 34 points and the second
is for 125 points. Calculate the average
percentage scored in the two competitions.
5.8. Julius needs to know the total length of line
in metres he has to buy for three washing lines.
The 3 lengths are available in centimetres.
5.9. Lesego has baked a batch of biscuits. She
puts 15 biscuits in a packet and Sipho receives
the remaining biscuits. Write two equations: How
many packets of biscuits were packed by
Lesego and how many biscuits Sipho received.
Chapter 2 Understanding a
problem and using a
computer to solve it

Introduction
This chapter introduces you to the
basic goal of this book –
understanding problems and how to
solve them. We’ll start by introducing
problems encountered in everyday life
situations, and then move on to
problems that can be solved using a
computer.

Outcomes
When you have studied this chapter, you should be able
to:
read and analyse a problem to understand
exactly what it is that needs to be solved,
understand how a computer processes data,
name the steps to find an excellent and
efficient solution for any problem, and
understand what an algorithm is and how it is
used to solve a simple problem.

1 Problem solving
Before you can learn how to solve a problem using a
computer, it’s essential to understand what the problem
is! You need to read the problem statement a number
of times to ensure that you understand what is being
asked before attempting to solve the problem.

These are the steps you follow to ensure you


understand a problem:

read the problem carefully,


understand what the problem entails, and
only then write down the steps to solve the problem.

An everyday example would be getting to class in the


morning.

Write down the steps to take from waking up in the


morning until you get to class.
The problem statement is very simple, and once you’ve
read it you understand what is being asked. However,
you now need to write down the steps:

1. Wake up.
2. Get out of bed.
3. Wash.
4. Put on clothes.
5. Make something to eat.
6. Eat.
7. Pick up my bag.
8. Go to class.

These are the basic steps. You can include more steps
to ensure that nothing is left out. You can also omit
some steps, such as making something to eat because
you eat later in the morning. Some steps can be
swapped around – you might wash after you’ve had
breakfast. Others, however, have to be done in a
specific order – it’s not possible to go to class before
waking up, getting out of bed, or putting on clothes!

But, most important, your steps must always be in


logical order!

These steps are called an algorithm, which is a set of


instructions in a specific sequence used to solve a
problem.
2 Understanding the
problem
When a programmer is faced with a problem to solve,
the problem is read carefully, and may be read a
number of times to be very sure that the problem is
understood. Deleting all unnecessary information from
the problem statement can help you arrive at the crux of
the problem. The examples below illustrate how this is
done.

Example 1
The Fresh Greengrocer store sells apples at 85 cents
each, pears at 65 cents each and oranges at 90 cents
each. Tumi has R15 and wants to buy 10 apples and 5
pears. Calculate the amount due.

To be able to calculate the amount due, she only needs


to know how many apples and how many pears to buy
and what their prices are. The information about the
oranges and the amount of money Tumi has aren’t
relevant to calculating the amount due.

Strike out all the redundant information and rewrite the


problem:
The Fresh Greengrocer store sells apples at 85 cents
each, pears at 65 cents each and oranges at 90 cents
each. Tumi has R15 and wants to buy 10 apples and 5
pears. Calculate the amount due.

Without all the unnecessary information, the problem


becomes:

The Fresh Greengrocer store sells apples at 85 cents


each and pears at 65 cents each. Tumi wants to buy 10
apples and 5 pears. Calculate the amount due.

As you can see, the problem statement is much easier


to read and understand.

Example 2
Calculate the floor area of the boardroom on the
second floor of the building next to the road to
Johannesburg. The length of the room is 7 metres and
the width is 4 metres. It is the largest room on the
second floor.

This problem statement can be simplified by deleting


the unnecessary information as follows:

Calculate the floor area of the boardroom that is on the


second floor of the building next to the road to
Johannesburg. The length of the room is 7 metres and
the width is 4 metres. It is the largest room on the
second floor.

The problem statement is now much easier to read and


understand:

Calculate the floor area of the board room. The length


of the room is 7 metres and the width is 4 metres.

A problem statement must include enough information to


enable the programmer to solve the problem. But if
some data (values) are missing, the problem must be
stated in such a way that the user will be able to supply
the missing data.

Example 3
The sum of two numbers must be calculated, but the
problem statement doesn’t supply the values. The
algorithm can ask the user to supply the values of the
numbers before calculating the sum.

The most important aspect of solving a problem using a


computer is writing the algorithm, or steps, to solve it.
An algorithm must be written in such a way that is it
unambiguous and precise. The computer cannot think
for itself – you need to tell the computer exactly what to
do. You should never assume that the computer will do
something that you haven’t explicitly specified in a step.
Another essential aspect of understanding a problem
statement is understanding the individual words in the
statement. This is illustrated in the following examples.

Example 4
A mail order company sells CDs and books to
customers all over the world. Customers enter the
name of a book or CD in the space provided on an
online form, and the mail order company immediately
lets the customer know if they have the item in stock
and what the price is. The system also informs the
customer of the packaging and posting costs, and
offers insurance on the parcel. Lastly, the customer is
informed about the dispatch date as well the estimated
arrival date of the parcel.

If the customer decides to order the item, his/her


details, including name, postal address and credit card
details, must be entered on the form.

The mail order company then checks the details


provided and informs the customer within a very short
time whether the transaction is approved or rejected. If
approved, the credit card is immediately debited with
the amount due.

What do they want me to do as the customer?


Order an item.
How should this be done?

I need to access the web page on the Internet, ask for


the specific item and then, if I want to order the item,
provide the necessary details.
What do I need to be able to do this?

I need to know if the item is available and if so,


provide my details. I must also have enough funds
available in my credit card account to pay for the item
plus additional costs.

Table 1: Specific words used in the problem


statement
Mail order A company that uses a catalogue or web page to
company advertise and sell items; once the customer has
ordered and paid for an item, it is posted to the
customer.

Item in The item is available for purchase


stock

Packaging The cost of packaging the item and paying the postage.
and posting Also called shipping costs.
cost

To insure The payment of an additional fee for which the


the parcel company promises to refund the customer should the
parcel not reach the customer.

Dispatch The date that the item will be posted


date

Credit card A bank account that can be used to buy items by


providing the account details, such as the number,
expiry date and security number

Check the The company will contact the bank online to ensure that
details the credit card details are valid and that there are
sufficient funds in the account to cover the purchase

Transaction The transaction can be completed


approved

Transaction The transaction cannot continue due to incorrect details


rejected or insufficient funds

Credit card The amount will be deducted from the customer′s


debited account and paid into the mail order company′s
with account.
amount

Example 5
The employees of a company called Taxi Service have
asked for a 7.5% increase on their salaries.
Management now needs to know how much the total
increase in salaries will be. Get the employee number
and current annual salary of every employee, then
calculate each employee’s salary with the increase.
Calculate and display the total additional cost in salaries
on the computer screen.

Table 2: Specific words in the problem statement


Employee A person who works for a company, in this case the
Taxi Service

Increase in An amount of money added to the current salary


salary

Annual salary The amount earned per year

Total The sum of all the salary increases for all employees
increase

Current The salary that is earned now


salary

What do they want me to do?

Display the total additional cost in salaries.


How should this be done?

Calculate the increase in salary for each employee,


then add all these amounts together to determine the
total additional amount the company will be paying on
salaries.
What do I need to be able to do this?

Get the employee number and current annual salary of


every employee and calculate the additional amount
that must be added to the salary.

Table 3: Descriptions of data


Description Variable name Data type
Employee number empNumber String

salary salary Real number

increase increase Real number

Total increase totalInc Real number

3 Data processing
An algorithm is divided into three phases:

1. What data you have available to solve the


problem,
2. How you’re going to solve the problem; what
steps you’re going to take, and
3. What the required result is.

Figure 1 illustrates the phases in an algorithm


schematically.

Figure 1
The phases in an algorithm

Both diagrams clearly indicate that the algorithm must


receive data (input) that must be processed to produce
meaningful results (output or information).

In other words:

Input is processed to produce meaningful output.


Data is processed to produce meaningful
information.

Example 6
The manager of a company asks a student to do some
part–time work for which he will be paid by the hour.
The student needs to know how many hours he has to
work at what rate of pay before he can calculate the
final amount he will receive.

In this case, the input (data) to the algorithm are the


hours and the hourly rate of pay. The input (data) must
be processed to give the output (information), which is
the amount the student will receive.

It is clear that the input (data) is meaningless unless it is


processed, because if the student knows how much he
will receive per hour, but does not know how many
hours he will work, the pay cannot be calculated! On
the other hand, if the student works for 20 hours but the
manager hasn’t told him how much he will earn per
hour, it is also meaningless.

Now it is possible to deduce the following:

Unprocessed data is meaningless.


Information is processed data.
Output is processed data.

Example 7
Let’s look at Example 3 again: Calculate the sum of
two numbers and display the result on the screen:

Input:Not available in the problem statement. The user


has to supply the numbers.

Processing:Add the two numbers to determine the sum.

Output:The sum as calculated in the processing phase


and displayed on the computer screen.

Note the following:

The value of the numbers must be available before


the sum can be calculated.
It is impossible to display the sum before it has been
calculated.
From this, it is clear that the steps in an algorithm must
always be written in logical order.

4 The problem–solving
approach
To summarise and formalise what we’ve discussed, the
following steps must be taken to find an excellent and
efficient solution.

4.1 Analyse the problem


You will be given a specification for the problem to be
solved. It is extremely important that you understand
the problem entirely before you try to solve it. Work
through the problem a number of times to make sure
that you understand what is expected of you. It is also
important that you take the available input, or data, into
account, as well as the expected output, or information.

It may sometimes be necessary to ask for more


information because the end user hasn’t provided
enough information to formulate a complete algorithm.
For example, a lecturer requests a class list containing
student names, student numbers and their final marks,
for the subject Principles of Programming 1 with the
subject code POP101A.

This seems like a reasonable request, but you don’t


actually have enough information. For instance, what
format does the lecturer have in mind for this report?

So you could ask questions such as:

Must the report be in student number sequence or in


surname sequence?
What must the format of the name be – for instance,
surname and initials or surname and first name?
How is the final mark calculated? Is it the average of
the year mark and examination mark, or is it based
on continuous evaluation? If it’s continuous
evaluation, what is the weighting of each test and
assignment? How many tests did the students
write? Are all the marks available?
What must the headings look like? Must the subject
name and code appear in the headings? In what
format must the date be printed?
Must the words FAIL, PASSED or PASSED WITH
DISTINCTION be printed next to the final mark?
Must the class average be printed at the end of the
report?

You can see that, as the programmer, you must


understand the problem completely before you can start
to develop the solution.
For complex problems, you can divide the task into
smaller subtasks. This will make the size and
complexity of every task easier to understand and to
handle.

4.2 Identify alternative ways


to solve the problem
There are usually many ways to solve a given problem;
however, some ways may simply be more effective
than others. It is important to look at the problem from
different angles and to consider different ways to solve
it. For instance, if you need to travel from Johannesburg
to Cape Town, there are many ways to reach your
destination: you can travel by road, rail or air; you could
go via Durban or even London! What might some of the
considerations be, such as cost and time? Try to think
of other ways of travelling from Johannesburg to Cape
Town.

4.3 Select the most


effective way to solve the
problem
Suppose you decide to travel by road from
Johannesburg to Cape Town. You could go through
Kimberley, Bloemfontein or Upington. You need to
identify the advantages and disadvantages of each
route. The length of each route will affect your choice.
Perhaps one route is much shorter than the others, but
there are a lot of road works on that route, or the
condition of the road is poor. These are the types of
conditions that will influence your final decision.

The same applies to computer logic. If you can write a


solution in 200 steps/statements or in 20 statements,
clearly the more effective solution is the 20–statement
one.

4.4 List all the steps


Now you must present all the steps to solve the
problem in an unambiguous way, but not yet in the
syntax of a programming language. At this stage you’re
planning how the processing must be done. Although
you must plan in a structured and unambiguous way,
you mustn’t focus on a particular programming language
– your plan must be applicable to any language.
Although there are various ways to plan a solution, we
will concentrate on writing algorithms in pseudocode to
specify the logic of a process. The algorithm is the
steps to solve a problem and the pseudocode is the
way in which these steps are expressed.

4.5 Evaluate the algorithm


for accuracy
The next step is to check the logic in your algorithm for
accuracy. This is called desk checking. Work through
the algorithm using various input values, exactly as the
computer would do, to test whether the algorithm
produces the correct output. This step is very
important. Using a variety of input values will test all
possibilities. If you identify any logic errors, you can
correct them at this early stage. This will prevent
problems when you start coding.

4.6 Pseudocode
Pseudocode is a way in which the algorithm steps are
written so that they can be followed easily and
understood. It is mostly given in simple English.
Therefore it is not yet in a computer programming
language, but it can be easily converted into a computer
language. Planning is never done in a programming
language as it may be too technical for the planning
stage.

Although there is no formal standard for pseudocode, it


should already be a structured process because the
programming code, which has to be derived from it,
must be precise.

Example:
Peter sells oranges, pears, guavas and apples. Last
week he sold 50 apples, 100 pears, 80 oranges and
some guavas. This week he sold twice as many items.
How many did he sell?

So to solve the problem:

1. Ask the question to obtain the number of guavas


sold last week.
2. Get the number of guavas.
3. Calculate the total number by adding the four
numbers to determine the total number sold last
week.
4. Multiply last week’s total by 2 to obtain this
week’s total.
Looking closely at this example, you can deduce that
the number of guavas, last week’s total and this week’s
total are the variables used to solve the problem. The
four steps taken to solve the problem are called the
algorithm.

A pseudocode solution is written in one statement per


line – or it can also be defined as one task per line.
However, if it’s a big task, it needs to be broken down
into several smaller tasks.

The initial pseudocode planning can be done in informal


English, as can be seen in the examples that follow.
Thereafter, the algorithm can be written in more
structured pseudocode, although it will not yet be
written in a programming language.

Example:
You want to print a particular greeting to members of a
forum.

Initial planning:
Writing the algorithm in a more structured manner:

However, planning is never done in a computer


language as indicated in the next example. Technical
knowledge of language–specific details should follow
only after planning the program logic in pseudocode has
been completed. You can clearly see that the structured
solution in pseudocode is much easier to follow than the
program in a programming language, such as the Visual
Basic program below.

4.7 What does pseudocode


entail?
There are six basic computer operations:

1. A computer can receive data.


• Read – from a file, database, or other
source

• Enter – via the keyboard, scanner or other


input device
2. A computer can produce information.
• Write – information to a file or a database
for instance

• Display – information to the screen

3. A computer can perform arithmetic.


• Use actual mathematical symbols or the
words for the symbol

• Add a number to a total

• total = total + number

• +, -, *, /

• Calculate and compute are also used.

4. A computer can assign a value to a variable.


• Three different cases are identified:

• To give variables an initial value

• Initialise, set

• To assign a value as a result of


processing

•?=?

•x=5+y

• To keep information for later use


• Save, store

5.

6.

The structured format of these operations will be


discussed in detail in the chapters that follow.

4.8 Writing an algorithm


Although it’s the focus of this book, writing algorithms in
pseudocode isn’t the only way to plan a computer–
related solution to a problem. For instance, you can use
flowcharts or Nassi Shneidermann diagrams (see
Appendix A ).
Example 8
Determine the weekly wage of an employee when the
hours he has worked and the hourly rate, are entered
by the user.

Prepare the logic to solve the problem:

1. Ask: How many hours did the employee work?


2. Get the number of hours.
3. Ask: What is the hourly rate of pay?
4. Get the hourly rate of pay.
5. Wage = number of hours * hourly rate of pay.
6. Show the wage on the screen.

The structured algorithm could be:

Exercises
1. Name the steps in solving a problem.
2. Write a detailed set of instructions, in
sequence, to complete the following three tasks.
Your instructions must be complete and in the
correct sequence so that a novice can perform
the tasks correctly from the instructions.
2.1. Bake a cake
2.2. Make a cup of tea
2.3. Buy a book
3. Study the following problems, delete the
redundant information and decide whether
enough information has been provided to obtain
an answer. Write down the steps to follow to
solve each problem:
3.1. The Lucky Company sells tickets at R5 each
for a lucky draw. Five friends bought tickets as
follows: Jessie, who doesn’t have much money,
bought two tickets, Judy bought 20 tickets and
Robin spent all her money on 80 tickets because
she is very positive that she will win the prize of
R1,000,000. Peter and Paul also bought tickets.
This lucky draw is very popular and a total of 750
000 tickets were sold. Calculate how much
money was spent by the five friends.
3.2. Lesego, who is in charge of all the stock in
the company, needs to buy a number of brushes
to replenish the stock on hand. Her office is
situated at the back of the ground floor of the
company’s building. The price of one brush is
R19.75. How much money will she have to
spend? Display the answer on the screen.
3.3. David has a number of dogs and always
buys food for them at the supermarket on the
first day of the month. Each dog eats 250 g of
dog biscuits per day. How much will David spend
on the first day of the month on dog food?
Display the answer on the screen. Assume that
he is able to buy the dog food per 50 g.
3.4. A college has a computer laboratory
available for students to practise their programs.
The laboratory opens at 8:00 in the morning and
closes at 17:00 in the afternoon from Monday to
Friday. Students are anxious to work the
maximum time available and are even willing to
start earlier in the morning and work later in the
afternoons. How much time will be available for
every student to practise during the week?
Display the answer on the screen.
Chapter 3 Write algorithms
in sequential steps

Introduction
Algorithms contain a combination of
three basic control structures –
sequence, selection and iteration.

In the sequence structure, each step is


executed once in sequential order. No
steps are left out and no steps are
repeated. Once all the steps are
executed, the problem is solved. If the
problem is not solved, this indicates
that there’s a logical error in the
algorithm. It may be that a step is
written incorrectly, is in the wrong
position or has been left out.
Outcomes
When you have studied this chapter, you should be able
to do the following for a problem that can be solved
with steps executed in sequential order:
identify all available input data and required
output,
draw an IPO chart for the problem statement,
write an algorithm in pseudocode to solve the
problem, and
test the logic of the algorithm with test data
using a trace table, to predict the output and
check that it’s correct.

1 Program planning
As you know, you can’t write a program in a
programming language unless you understand the
problem. You also need to plan how to solve it by
identifying the input and output, and setting out the
processing logic in an algorithm.

In this section, we'll discuss the planning of various


problems that can be solved simply by using steps
executed in sequence.

Example 1
Problem
Enter the name and age of a learner on the keyboard
and display the name and age with a legend – which is
an applicable explanation or heading to describe the
output – on the computer screen.

The first step is to read and understand the problem


very well, then identify

the available data (input)


what I need (output).

Planning
As the first part of the planning, you draw up a table
that contains a description of each input and output
item, together with their type and variable name.

Table 1: Input and output variables for Example 1


Description Type Variable name

Input Name of learner String name

Age of learner Integer age

Output Name of learner String name (same as input)

Age of learner Integer age


Programmers draw up what is known as an
Input/Processing/Output (IPO) chart, which enables
them to do better and more comprehensive planning,
which, in turn, enables the programmer to write
complete algorithms without errors. The Input and
Output columns in the IPO chart contain only the names
of variables, and the Processing column provides an
overview of the steps.

Table 2: IPO chart for Example 1


Input Processing Output

name Prompt to read input fields name

age Enter input fields age

Show name and age on screen

The preparation is now done, so it’s possible to write a


detailed algorithm that contains every step to solve the
problem.

Algorithm
The steps in the algorithm will be processed in the
order that they are given, one after the other, to provide
the following output on the screen:

Provide the name of the learner John

Provide the age of the learner 18

The name of the learner is John

The age of the learner is 18


In this example, the input data was the name John and
the age 18. However, you can use other test data to
test this algorithm.

In this book, we’re going to write algorithms in a


specific way using predetermined words.

An algorithm has the following properties:

Every algorithm has a name that describes the


function or purpose of the algorithm. The algorithm
in Example 1 is called ShowDetails. The name of an
algorithm starts with an uppercase letter.
The last statement or step is always end.
The statements or instructions between the name of
the algorithm and the end are called the body of the
algorithm.
A ~ (tilde) indicates that a comment, which explains
the code, will follow. A comment can be on a
separate line or can follow in the same line as an
instruction. A comment typically explains difficult
code or why you’re including a specific instruction.
However, comments can contain any text you wish
to include. A comment can be included anywhere in
an algorithm.
Display means that a message or the contents of a
variable are displayed (shown) on the computer
screen.
Enter indicates that data must be entered via the
keyboard.
Calculation can also be done using equations. In the
algorithm in Example 2 , the metre and centimetre
variables will get new values.

When the ShowDetails algorithm is processed from


beginning to end, the following happens:

1. Words that follow the ~ sign are not executable


because they’re comments that explain what is
happening or going to happen. In this case, the
purpose of the algorithm is explained.
2. The display “Provide the name of the learner”
statement means that something must be shown
on the computer screen. In this case, the text
inside the quotes is displayed.
3. The enter name statement causes the computer
to show a prompt on the screen so that the user
can use the keyboard to type a name. This name
is stored in the variable called name.
4. The next two statements enable the user to enter
the age of a person to store in the variable called
age.
5. The display “The name of the learner is”, name
statement displays the results on the screen as
follows − the words in quotes are shown exactly
as given, whereas name is a variable so its
content is displayed. The output is The name of
the learner is John. We have now displayed a
constant and the content of a variable.
6. The same rules apply to the next statement,
which displays The age of the learner is 18.
7. The comments on the right-hand side indicate
that the details in each display statement must be
shown on a new line on the screen.
8. Note how the body of the algorithm is indented.

Example 2

Problem
Enter the distance between two trees in kilometres.
Calculate and display the distance in metres and then
calculate and display the distance in centimetres.

Planning
Table 3: Input and output variables for Example 2
Description Type Variable name

Input Distance in km Integer kilometre

Output Distance in km Integer kilometre

Distance in m Integer metre

Distance in cm Integer centimetre

Table 4: IPO chart for Example 2


Input Processing Output

kilometre Prompt to read kilometre kilometre

Enter kilometre metre

Calculate metre centimetre

Calculate centimetre

Display metre

Display centimetre
Note that the IPO chart does not contain detailed
processing steps.

Algorithm

Note the indenting in the algorithm to enhance


readability.

The input data to test this algorithm will be 3 kilometres.

Output:
Please provide the distance in km. 3

3 km is equivalent to 3000 m and to 300000 cm


If the last display statement is replaced by the following
three display statements, the output will change as
follows:
New output:

Please provide the distance in km. 3

Distance = 3 km

Equivalent distance in cm = 300000 cm

Equivalent distance in metres = 3000 m

2 Testing the logic of an


algorithm
Even when carefully planned and written correctly,
programmers can’t assume that their algorithm is error-
free and will produce the intended results in a form that
is easy to read and understand. It is very important to
test this logic for correctness and readability.

To achieve the intended results, the programmer


compiles a set of test data to test the logic, as we did
in Examples 1 and 2. The test data must include a
sample of every category of correct data and incorrect
data. The test data must also be realistic. At this stage,
our test data is simple, but more complicated
algorithms will need more test data to ensure that no
errors will occur.
The logic can also be tested using a trace table, also
known as desk checking or a walkthrough table.

Example 3

Problem
Enter the length and the width of a tennis court in
metres, then calculate and display the perimeter and
the area of the tennis court.

Planning
Table 5: Input and output variables for Example 3
Description Type Variable name

Input Length of court Real length

Width of court Real width

Output Perimeter of court Real perim

Area of court Real area

Table 6: IPO chart for Example 3


Input Processing Output

length Prompt for input fields perim

width Enter input fields area


Calculate perimeter and area

Display output fields

Algorithm

Trace table
The input data to test this algorithm is length = 30 and
width = 10.

Table 7: A trace table for the CalcTennisCourt


algorithm
Instruction length width perim area Output

display Please enter


length

enter 30
display Please enter width

enter 10

calculate 80
perim

calculate 300
area

display The perimeter of


the tennis court is
80 metres

display The area of the


tennis court is 300
square metres

The instructions are listed in the left column, followed by


the variables and the output. If, for instance, an
alphabetic character is entered for the length, it will not
be able to do the calculation and an error will occur.

Output:
Please enter length 30

Please enter width 10

The perimeter of the tennis court is 80 metres

The area of the tennis court is 300 square


metres
Note that the algorithm can also accept and display real
values. The length could have been 30.5 and the width
10.2, which results in 81.4 metres and 311.10 square
metres.

Example 4

Problem
Enter two integers on the keyboard and calculate and
show the average of these two integers on the screen.

Planning
Table 8: Input and output variables for Example 4
Description Type Variable name

Input First number Integer num1

Second number Integer num2

Output Average Real average

Table 9: IPO chart for Example 4


Input Processing Output

num1 Prompt for num1 and num2 average

num2 Enter num1 and num2


Calculate average

Show average on the screen

Algorithm

If the two numbers used as input data were 24 and 40,


the output would be:

Enter first number 24

Enter second number 40

The average of the two numbers is 32

Example 5

Problem
Jason works as a part-time assistant in a bookshop and
receives an hourly wage. Enter the number of hours he
worked for a specific week, as well as the pay rate per
hour. He has to pay R8 towards the recreation club.
Calculate and display how much take-home pay he’s
earned for the week.

Planning
Table 10: Input and output variables for Example 5
Description Type Variable name

Input Hours worked Integer hours

Rate of pay Real rate

Output Weekly wage Real wage

Table 11: IPO chart for Example 5


Input Processing Output

hours Prompt for input fields wage

rate Enter hours and rate

Calculate wage

Display wage on screen

Algorithm
The input data used to test this algorithm: hours worked
= 24 and rate of pay = R12.

Output:
Provide number of hours Jason worked 24

Provide rate of pay 12

Jason earned R280 for the week.


Note that the rate can also be a real value, which would
result in a real answer.

Example 6
Tebogo earns a monthly salary, which she divides at the
beginning of each month into amounts according to her
needs. She pays R450 on rent for her room and the
remainder of the money is divided as follows: 50% for
food, 20% for clothes, 15% for transport, 5% for
charity and the remaining amount for pocket money.
Enter her monthly salary, which is never less than R1
800, on the keyboard and then calculate and display
how much money she has available for the various
categories.

Planning
Table 12: Input and output variables for Example 6
Description Type Variable name

Input Monthly salary Real salary

Intermediate Money to divide Real remainder

Output Room Real room

Food Real food

Clothes Real clothes

Transport Real transport

Charity Real charity

Pocket money Real pocket

Note that an intermediate variable can be used to assist


with the calculations. It is not part of the input or the
output.

Table 13: IPO chart for Example 6


Input Processing Output
salary Prompt for salary room

Enter salary food

Calculate various categories clothes

Display output fields transport

charity

pocket

Algorithm

This algorithm is tested with a monthly salary of


R2 000. Note that the Rand sign (R) is not included in
the algorithm, neither is the space – the thousands
separator).

Output:
Provide Tebogo’s monthly salary: 2000

Tebogo divided her salary as follows:

Room R450.00

Food R775.00

Clothes R310.00

Transport R232.50

Charity R77.50

Pocket money R155.00

Example 7
At The Friendly Store, items can be bought individually,
in which case the full amount is paid. However,
customers can also buy items in bulk packages of 50 or
100, in which case a discount per item applies. There’s
a 10% discount per item on bulk packages of 50, and a
12.5% discount per item on bulk packages of 100.

Enter the amount for one item and then display the
following:
The amount for a package of 50 items
The saving on one item in a bulk package of 50
The total savings for a bulk package of 50
The amount for a package of 100 items
The saving on one item in a bulk package of 100
The total savings for a bulk package of 100

Choose your own descriptive names for variables. You


may assume that the input entered will be valid and
correct.

Planning
Table 14: Input and output variables for Example 7
Description Type Variable
name

Input Price for one item Real amtOne

Intermediate Discount price for one item if Real amt50_One


50 are bought

Discount price for one item if Real amt100_One


100 are bought

Output Price of bulk pack of 50 Real amt50


items

Price of bulk pack of 100 Real amt100


items

Amount saved on one item Real save1


for bulk pack of 50
Amount saved on one item Real save2
for bulk pack of 100

Total amount saved on bulk Real save50


pack of 50

Total amount saved on bulk Real save100


pack of 100

Table 15: IPO chart for Example 7


Input Processing Output

amtOne Prompt for input value amt50

Enter amtOne amt100

Calculate output values save1

Display output save2

save50

save100

Algorithm
Complete the following trace table:
Example 8
At the EAT-A-LOT restaurant, customers dish up their
own food and have the plate weighed in kg (2 decimal
positions). The total weight of the plate and the food
must be entered. The plate weighs 1.05 kg, which is
subtracted from the total weight. The customer has to
pay R7.35 per 100 g of food, and 14% VAT is added to
the total. Display the weight of the food in kg as well as
the amount due.
Planning
Table 16: Input and output variables for Example 8
Description Type Variable name

Input Weight of food and plate in Real weightFoodPlate


kg

Intermediate Weight of food alone per Real weightFood100G


100 g

Output Amount due Real amtDue

Weight of food in kg Real weightFoodKG

Table 17: IPO chart for Example 8


Input Processing Output

weightFoodPlate Prompt for input value amtDue

Enter the input value WeightFoodKG

Calculate the output values

Display the output

Algorithm
3 Calculating the outcome
of an algorithm
It is often necessary to determine the exact outcome of
a set of instructions in an algorithm or program. Usually
these statements include tricky calculations so the
programmer needs to ensure that the calculation has
been done correctly and must also know what result to
expect. This could have been done with a trace table,
but we only need to test the calculations, not the entire
algorithm, so we can use a shorter method. We’ll study
two examples to explain this method.

Study the following statements. Note the exact output


that will be displayed after these statements have been
executed.

Example 9

Draw a table that contains only the variables used in the


calculations:

A B C

After the first statement is executed, the value of A will


be 3.

A B C

After the next statement the value of B will be 7.


A B C

Now the calculation must be done to determine the new


value of A.

A gets a new value of 6 to replace the previous value of


3.

A B C

Now the calculation must be done to determine the


value of C.
A B C

33

The last statement:


display “The value of C is ”, C

will first display the content of the legend followed by


the value of the variable as follows:

This will be the answer to the question because it is the


only output displayed by the algorithm. The table
assisted us only in calculating the values of the
variables as the statements were executed.

Example 10
Use the same set of instructions as Example 9, but
change the display statement to

display “The value of A plus B is ”, A + B

Then the output will be:

The value of A plus B (6 + 7 = 13, as can be seen in the


table) will be calculated before the result is displayed.

Example 11
Use the same instructions again, but change the display
statement to show the values of all three the variables
in one line:

display “A = ”, A, “ B = ”, B, “ C = ”, C

Then the output will be:

How did we insert the spaces between the three


answers?

Exercises
Question 1
In each case, indicate the variables used, draw an IPO
chart and write an algorithm to solve the problem. Test
your algorithm by doing a trace table for every odd-
numbered question.

1.1. Enter the name and price of an item in the


shop on the keyboard, then show the information
on the computer screen with an appropriate
legend.
1.2. Enter two integers. Calculate and show the
sum, difference and product of these two
integers on the screen.
1.3. Enter the number of rows of chairs in the city
hall as well as the number of chairs per row.
Calculate and display the total number of chairs
in the hall.
1.4. Enter Ridwaan’s height in metres and
centimetres. Calculate and display his height only
in centimetres (1 metre = 100 centimetres).
1.5. Nomsa bought a number of the same items
at a shop. Enter the quantity she bought and the
unit price per item. Calculate the amount due by
multiplying the number by the unit price and then
adding 14% VAT to the amount. Display the final
amount she owes on the computer screen.
1.6. Jane is a typist who works freelance and
she charges the following rates:
A page typed in single spacing, R4.75
A page typed in double spacing, R3.50
The user must enter the number of pages she
typed in single spacing and the number of pages
she typed in double spacing. Calculate the
amount that must be paid by the customer. She
saves 15% of this amount to buy supplies.
Display the net amount she earned for her work.
1.7. Enter values of the minimum and maximum
temperatures for a given day, then calculate the
average temperature of the day. Show the
answer on the computer screen.
1.8. Freedom bought a number of eggs. Enter
the number of eggs and the cost price of one
egg. Unfortunately 5% of the eggs broke, but he
sold all the other eggs at cost price + 25%.
Calculate and show the total profit on the
computer screen. You may assume that there will
not be a loss.
1.9. Enter any integer. Calculate double, half, a
third and a quarter of the number and show the
result on the screen. The data type of the result
must be real.
1.10. Enter the number of pages in a set of notes
as well as the number of students who must
receive these notes. Paper is sold in reams of
500 sheets. Enter the price of a ream. You have
to add two additional sets of notes – one for the
lecturer and the other for the subject file. Also
bear in mind that you may have a trial run to see
if the notes are printing correctly. Because these
notes are printed for educational purposes, the
dealer gives a discount of 7.5% on the price of
the paper. Calculate and display the total cost as
well as the cost per set of notes; disregard the
sets for the lecturer and subject, and the paper
used for the trial run. You may assume that you
need not calculate full reams of paper.
1.11. The basic price for a phone call of three
minutes is 50 cents. Enter the duration of a
phone call in minutes. For every minute above the
basic three minutes, an additional amount of 15
cents per minute is charged. Add 14% VAT.
Calculate and display the price of a phone call.
You may assume that the call will be more than 3
minutes.
1.12. Henry rents a trailer to move stock to a
store. The basic cost is R200 per day. He also
pays a specific amount per kilometre travelled,
entered by the owner. The owner also has to
enter the kilometres and the number of days that
Henry rented the trailer. Determine and show the
amount due on the screen.

Question 2
Study the following variables with their initial values, and
the statements that follow, which are based on the
variables and their initial values. Display the exact
output that will be displayed after the statements have
been executed.

Description Data type Variable name Initial value

Gross monthly salary Real salary R15234.50

Tax payable Real tax

Net monthly salary Real netSal

Percentage tax payable Integer taxPerc 32

Statements

Question 3
Study the following statements. Display the exact output
that will be displayed after these statements have been
executed.

3.1
3.2

3.3

3.4
3.5
Chapter 4 The selection
control structure: Part 1

Introduction
The complexity of a problem may be of
such a nature that it cannot be solved
by simply applying statements in
sequence. An algorithm may therefore
include the possibility of providing for
different options that could change the
flow of statements in the algorithm. To
enable the programmer to include this
type of logic in an algorithm, a
selection (decision) control statement,
that is based on relational and logical
operators, can be included. The
selection control structure can be a
simple if statement or a more
complicated if–then–else statement
or compound statement.
Outcomes
When you have studied this chapter you should be able
to:
determine the results of relational conditions,
evaluate expressions that contain logical
operators,
write a simple if statement in pseudocode to
test a condition,
write an if–then–else statement in
pseudocode,
prepare test data to test all possible
conditions for a program that contains
decision structures,
write algorithms containing
• simple if statements,

• if–then–else statements,

• compound if statements

• Boolean variables,

code defensively and do data validation


wherever possible.

1 Relational operations
Computers are able to compare two values.
Expressions that compare operands (values or
variables) are called relational expressions. The
outcome or result of such a comparison always yields a
Boolean value – that is, true or false.

Examples:

5 > 3 result: true

16 = 5 result: false

Table 1: The operators used in relational


comparisons
Pseudocode symbol Description Example

= Equal to A= 5

< Less than number < 97

> Greater than totalAmount > 100

<= Less than or equal to noStudents <= 50

>= Greater than or equal to weight > = 75

<> Not equal to quantity <> 17

All these relational operators have equal priority, but


the mathematical operators have a higher priority than
the relational operators.
Examples:

Determine whether the following expression is true or


false:

Exercises
Evaluate the following expressions:

1. a + t <> (a + b) * 4 where a = 4, b = 17 and t = 20

2. k ^ 2 <= m mod 5 + 29 - n where k = 5, m = 63, n = 7

3. (x \ 8 -2) + 3 > y / 12 mod 2 where x = 59, y = 96


4. d + 4 * g / 2 < g * 3 + 14 where d = 3, g = 24

Note
In computing and mathematics, the term ‘evaluate’ is
often used to mean ‘find the result’ – for example, the
equation evaluates to zero or another value, or it
evaluates to True or False.

2 Logical operations
A logical operator joins two Boolean expressions to
yield a Boolean answer, either true or false.

Table 2: The operators used in logical operations


Pseudocode Description Example Result Precedence
symbol

NOT Yields the NOT True False 1


opposite NOT True
False

AND Both True AND True 2


expressions True False
must be True True AND False
to False False
yield True False
AND True
False
AND
False
OR Only one True OR True 3
expression True True
must be True True OR True
to False False
yield True False OR
True
False OR
False

Example:

To illustrate the OR, suppose a person needs either an


ID document or a driver’s licence, but not both, to enter
an event (outcome to be true). However, to illustrate the
AND, if the person needs to provide an ID document as
well as a letter of approval before entering the event,
both documents must be provided before the person
may enter.

The order of precedence is indicated in the last column


– that is, processing is done in the following order:

from left to right


NOT
AND
OR

When different operators are combined in one


expression, all the mathematical operators will be
processed first, then the relational operators, and finally
the logical operators.

However, the order can be changed using parentheses.


For example, if an OR must be processed before an
AND, parentheses can be inserted.

Example:

Let A, B, C and X be Boolean variable with the following


values:

A = True, B = False and C = True

Evaluate the equation:

X = A OR B AND C

Substitute:

X = True OR False AND True

AND is done first:

X= True OR False

= False

Use parentheses:
X= (A OR B) AND C

= (True OR False) AND True

= True AND True

Tables 3, 4 and 5 illustrate the order of precedence of


all operators.

Table 3: Highest priority, from left to right


Operator Description Example Result Precedence

^ Exponentiation 2 ^4 16 1
(to the power of)

- Negation -True False 2


--6 +6

*/ Multiplication and 5*7 35 3


division 72 / 8 9

\ Integer division 37 \ 5 7 4
mod Modulus 37 mod 2
arithmetic 5

+- Addition and 4+7 11 5


subtraction 14 - 5 9

Table 4: Second highest priority, from left to right


Operator Description Example

= Equal to A= 5
< Less than number < 97

> Greater than totalAmount > 100

<= Less than or equal to noStudents <= 50

>= Greater than or equal to weight >= 75

<> Not equal to quantity <> 17

Table 5: Lowest priority, from left to right


Operator Description Example Result Precedence

NOT Yields the NOT True False 1


opposite NOT False True

AND Both True AND True 2


expressions True False
must be True True AND False
to False False
yield True False AND
True
False AND
False

OR Only one True OR True 3


expression True True
must be True True OR True
to False False
yield True False OR
True
False OR
False
Examples
Evaluate the following expressions:

1. D OR K AND NOT S where D = TRUE, K =


FALSE, S = TRUE
Substitute:
TRUE OR FALSE AND NOT TRUE

TRUE OR FALSE AND FALSE

TRUE OR FALSE

TRUE

2. M > 7 AND D < S ^ 2 where M = 7, D = 8, S = 4


Substitute:
7 > 7 AND 8 < 4 ^ 2

7 > 7 AND 8 < 16

FALSE AND 8 < 16

FALSE AND TRUE

FALSE

3. D < (E + 7) AND G OR (A * C) >= (D – E + C)


where A = 5, C = 12, D = -15, E = -17, G =
FALSE
Substitute:
-15 < (-17 + 7) AND FALSE OR (5 * 12) >=
(-15 – -17 + 12)
-15 < (-17 + 7) AND FALSE OR (5 * 12) >=
(-15 + 17 + 12

-15 < - 10 AND FALSE OR (5 * 12) > = (-15


+ 17 + 12)

-15 < -10 AND FALSE OR 60 > = (-15 + 17 +


12)

-15 < -10 AND FALSE OR 60 > = (2 + 12)

-15 < -10 AND FALSE OR 60 > = 14

TRUE AND FALSE OR 60 > = 14

TRUE AND FALSE OR TRUE

FALSE OR TRUE

TRUE

Exercises
Evaluate the following expressions where A = 5, B = 7,
C = 12, D = -4, E = TRUE and F = FALSE:

1. A * 3 >= B – 14 \ 3 AND F OR C < = D + 3


2. NOT F OR E AND D + C = A
3. (C – D) * 2 <> A + B OR E AND F OR B > D + B
^2
4. D = C MOD 5 AND NOT F OR NOT (A + D <= A
– D)
3 The simple If statement
If statements are also called if-then statements
because they cause the computer to test a condition
before executing the ‘then’ part of the statement. If the
condition is true, the ‘then’ part is executed. If not, the if
statement is skipped entirely and the computer
continues executing the rest of the program.

If statements are best explained using an example:

If an employee has worked more than 45 hours during


the past week, a bonus of R300 must be added to his
or her wages.

Pseudocode

Explanation of the above three lines:

if hours > 45 then

∼This statement tests if the hours worked exceed


45.

wage = wage + 300


∼If the test is true (the employee has worked more
than 45 hours),

∼the previous value in the wage variable is replaced


by an increased

∼wage of R300 more.

endif

∼This line ends the if structure and the execution of


statements will

∼continue after the endif statement, regardless of


the outcome of

∼the if test.

If the employee has not worked more than 45 hours,


the execution of statements will continue after the endif
key word. In other words, the statement to increase the
wage is skipped.

If statement syntax

Example
This algorithm can also be represented as a flowchart.

Figure 1 Flowchart of a simple If statement

Notes
There can be any number of statements in the body
of an if statement – between if and endif.
The statements in the body of an if statement
execute only if the condition is TRUE.
Statements within an if statement are always
indented to aid the readability of the algorithm.
If and endif are written in the same column, whereas
the body of the if statement is indented.
An if statement always yields a Boolean value, so
the result is always TRUE or FALSE.

It is also possible to test whether a specific condition is


not true by inserting the word NOT before the condition.

3.1 Testing a program that


has an If statement
Study the following example:

Lerato bakes cakes that she sells per slice. She cuts
10 slices per cake. She calculates the amount spent on
the ingredients, electricity and packaging material. She
adds 30% to the amount spent and then she calculates
the price of a slice of cake. The user will enter the
amount spent per cake, then the algorithm will calculate
and display the price of a slice. She always sells the
slices in full Rand amounts. For example, if the
calculated price is R3.25, then the selling price will be
R4. In other words, cents are always rounded up to the
next Rand.

Planning

Intermediate variables are used in this solution to help


with the calculations. These intermediate variables
aren’t part of the input or the output.

Table 6: Input and output variables for


CalcCakePrice algorithm
Description Type Variable name

Input Cost of cake Real expense

Intermediate Cake selling price Real cakePrice

Price per slice Integer slicePriceInteger

Price per slice Real slicePriceDecimal

Output Price of slice Integer slicePriceInteger

Table 7: IPO chart for CalcCakePrice algorithm


Input Processing Output

expense Prompt for expense slicePriceInteger


Enter expense
Calculate
slicePriceInteger
Display slicePriceInteger

Algorithm

Test the program using a


manual calculation
Use as test data:

Expense R18.60

Increase by 30% R24.18


Gross price per slice R2.418

Integer division results in R2 per slice of cake

Because there is a difference in integer and


decimal prices, R1 will be added to the integer
result to give the selling price for a slice of cake.

Selling price per slice R3

Note that MOD could not be used in this


example because the remainder part is a real
value and not an integer.

Table 8: The inclusion of an If statement in a


trace table
The instruction is listed in the leftmost column,
followed by the variables, the outcome of the if
statement, and finally the output, as shown in
Table 8.

Output:
Provide the price of the cake 18.60

The price of a slice of cake is R3


Whenever there’s an if statement in an algorithm, you
should prepare test data that tests whether all possible
outcomes of the if statement work correctly.

3.2 Examples of simple If


statements
In this section we’ll discuss the planning of various
problems that can be solved using simple if statements.

Example 1
Problem

John wishes to buy a number of pencils at a given price.


The seller must enter the unit price and the number of
pencils bought. If John buys 25 pencils or more, he’ll
receive a discount of 7.5%. Calculate and display the
amount due by John.

Planning

Table 9: Input and output variables for Example 1


Description Type Variable name

Input Number of pencils Integer number

Price of one pencil Real price

Output Amount due Real amount

Table 10: IPO chart for Example 1


Input Processing Output

number Prompt to read input amount


values
Price Enter input values
Calculate amount
Display amount

Algorithm
Test the program twice using:

number = 16, price = R3.50 (fewer than 25


pencils)

number = 30, price = R2.25 (equal to or more


than 25 pencils)
Output:
Provide the number of pencils bought 16

Provide price of one pencil 3.50

The amount due is R56

Provide the number of pencils bought 30

Provide price of one pencil 2.25

The amount due is R62.44


Example 2
Problem

The mark obtained by a student is entered. If the


student has passed (50% or more), the mark must be
displayed as well as a message that indicates that the
student has passed. But if the mark is less than 50%,
the mark and a message indicating that the student has
failed must be displayed.

Planning

Table 11: Input and output variables for Example 2


Description Type Variable name

Input Mark obtained Integer mark

Output Mark obtained Integer mark

Message String message

Table 12: IPO chart for Example 2


Input Processing Output

mark Prompt to read mark mark


Enter mark message
Price Test mark to determine
message
Display output fields
Algorithm

Test the program twice with marks of 45 and 69


respectively.
Output:
Provide mark obtained 45

The mark is 45. Result = fail

Provide mark obtained 69

The mark is 69. Result = pass


Note that the message was initially set to “pass” and
then tested. If the mark was not equal to or more than
50, the message was changed to “fail”.

Exercises
Do the planning and write an algorithm to solve the
following problems. Prepare test data for the examples
to test all possibilities, and draw a trace table for each.

1. Henry rents a trailer to move his furniture to his


new house. The basic cost is R200 per day plus
a specific amount that must be entered by him
per kilometre travelled. He also has to enter the
distance in kilometres. If Henry travelled less
than 50 kilometres, an additional surcharge of
5% is payable on the amount due for the
distance. However, if he used the trailer for more
than 400 kilometres, he receives a discount of
12% on the amount due for the distance.
Calculate and display the amount due. Hint: Use
two different if statements in your algorithm.
2. Jessie and Sally want to buy a large pizza to
share. Enter the cost of the pizza and the
amounts that Jessie and Sally each have in their
purses. If they have enough money, display a
message that indicates that they can buy the
large pizza. However, if they don’t have enough
money, display a message saying that they have
to buy a small pizza.
3. Harry earns R16.50 per hour. If he works more
than 40 hours, he receives an extra R10 per
hour. The employer enters the number of hours
Harry has worked. Calculate and display Harry’s
total wages.
4. Dumisane works at a company where all the
employees receive a bonus of R500, except the
employees in Department 7, who receive a bonus
of R550. Enter his gross salary and his
department number. Calculate the gross (total)
income. Subtract 20% of the gross income for
tax. Determine and display Dumisane’s net
income on the screen.

4 The If-then-else statement


We’ve tested a specific condition and, if the condition
proved to be TRUE, we processed certain statements.
It is, however, possible to process other statements
when the condition is not TRUE, but FALSE.

Suppose all the employees in a company receive an


increase of 8%, but the employees in Department A,
which performed the best, receive an increase of 10%.
This can be accomplished by means of an if statement
that contains an else clause, as shown in the following
example.
Figure 2 Flowchart of an If–then–else statement

4.1 Examples of If-then-else


statements
In this section, we’ll discuss the planning of various
problems that can be solved using if–then–else
statements.
Example 3
Problem

Angelina and Freedom are taking part in the final round


of a competition. One rule of the competition is that
judges may not assign equal points to competitors at
this stage. Enter the number of points that each
competitor obtains. Compare the points and determine
who the winner is. Display the winner’s name and
number of points on the screen.

Planning

Table 13: Input and output variables for Example 3


Description Type Variable name

Input Angelina’s points Integer pointA

Freedom’s points Integer pointF

Output Winner’s points Integer pointW

Winner’s name String winner

Table 14: IPO chart for Example 3


Input Processing Output

pointA Prompt for points winner

pointF Enter points pointW


Determine winner

Display winner and pointW

Algorithm

Test the program

Angelina obtained 175 points and Freedom


obtained 179 points.
Output:
Provide points for Angelina 175

Provide points for Freedom 179


The winner is Freedom and the winning points
are: 179

Example 4
Problem

Dennis loves reading books and you have been asked


to calculate how many days he will need to read a given
book, by writing an algorithm to solve the problem.
Enter the number of pages in the book and the number
of pages that he is able to read per day. Calculate and
display how long it takes to read the book. You also
need to determine whether it is possible for him to read
five books with the same number of pages during his 14
days of holiday. Display the answer.

Planning

Table 15: Input and output variables for Example 4


Description Type Variable name

Input Pages per book Integer bookPages

Pages per day Integer dayPages

Intermediate Days to read 5 books Real days

Output Days per book Real bookDays

Message String message


Table 16: IPO chart for Example 4
Input Processing Output

bookPages Prompt for input values bookDays

dayPages Enter input values message

Calculate bookDays

Determine message

Display output values

Algorithm

Test the program


Book has 120 pages

Dennis can read 50 pages per day


Output:
Provide number of pages per book 120

Provide pages read per day 50

Dennis takes 2.4 days per book

Dennis can read five books during the holidays.

Exercises
1. In each of the following cases, do the planning
and write an algorithm to solve the problem:
1.1. The Great College offers two different
courses in Programming that are offered as self-
study courses in which the lecturer assists. The
student can decide beforehand how many weeks
he or she wants to study. The code of the first
course is A, and the code for the second is B.
You may assume that the user will only enter an
A or a B. The price for course code A is R234
per week, whereas the price for the other course
is R287.50 per week. The student has to enter
the course code and the number of weeks of
study. Calculate the total price of the course and
display the course code and total price on the
screen.
1.2. Spectators can purchase tickets to attend a
soccer match at R15 per ticket. Anyone who
buys eight or more tickets pays only R12.50 per
ticket. Prompt the user to enter the number of
tickets bought, then calculate and display the
amount due.
2. Describe the variables and write only the if
statement for the following. You may choose your
own variable names if they haven’t been
specified.
2.1. The weights of two dogs, Fluffy and Terry,
are available. Display the name of the dog that
weighs more than the other dog.
2.2. An employee’s salary, called empSalary, has
been entered. Determine and display a message
to indicate whether this person needs to pay
income tax. Only people with an income of more
than R3 000 per month have to pay tax.
2.3. Tom decided that he must have one shirt for
every pair of pants. Determine whether this is
true and display an appropriate message.
2.4. Josie wants to go to the movies, but isn’t
allowed to go unless she’s done her homework –
use a Boolean variable for this – and has R10 to
pay for the ticket. Display a message to indicate
whether she can go.
2.5. Test a student’s mark. If the mark is more
than 47, increase the mark by 2.5%, otherwise
decrease the mark by 5.7%. Display the new
mark.
3. Study the following code:

3.1. What will be displayed if the code is


executed and the following values apply?
A = 5 and B = 7
3.2. What will be displayed if the code is
executed and the following values apply?
A = 12 and B = -9

5 Compound If statements
Programmers often find that more than one condition
must be tested before the result can be true. A
compound if statement, which is based on logical
operators, can be used to resolve this.

Example

If a person is 18 years old or older and has a driver’s


license, this person may drive a car.
Figure 3 An AND compound If statement
represented as a flowchart

The result of this compound test is true only when both


the conditions are true. If one or neither of the
conditions is true, the result is false.

Example
If an employee is a Grade C employee or has worked
for the company for more than five years, a special
bonus of R1 000.00 is awarded to the employee.
Figure 4 An OR compound If statement represented
as a flowchart

For the result of this compound test to be true, at least


one of the conditions must be true. If neither is true, the
result is false.

In cases like this, where the if statement contains more


than two conditions, it is advisable to use parentheses
to indicate the order in which the tests must be done,
since the tests in the parentheses are done first.

Or, depending on the question/conditions:

If parentheses are not used, all the AND operators are


evaluated from left to right and only then will the OR
operators be evaluated from left to right.

The word NOT can also be used, but must be handled


extremely carefully, because a beginner programmer
might achieve the opposite result. NOT has a higher
precedence than AND and OR, which means it will be
evaluated first. Refer to Table 2 where these logical
operators are summarised in a truth table.

Example 5
This example shows the planning for a problem with a
compound if statement.

Problem

Everybody in the town Little River will be attending the


circus over the weekend. Do the planning and write an
algorithm to determine the entrance fee for a particular
person. Persons younger than 12 or persons 60 and
older receive a 25% discount.

The user must enter the normal entrance fee and the
person’s age in years as an integer value. Calculate and
display the entrance fee on the screen.

Planning

Table 17: Input and output variables for Example 5


Description Type Variable name

Input Entrance fee Real fee

Person’s age Integer age

Output Actual fee Real actFee


Table 18: IPO chart for Example 5
Input Processing Output

fee Prompt to read fee and actFee


age

age Enter input values

Determine actFee

Display actFee

Algorithm

Test the program

Test the program twice:

Fee of R50 and an age of 9 years


Fee of R80.50 and an age of 32 years
Output:
Enter the normal fee 50

Enter the age in years only 9

This person must pay an entrance fee of R37.50

Enter the normal fee 80.50

Enter the age in years only 32

This person must pay an entrance fee of R80.50

Exercise
Write pseudocode for the following:

Values for the variables A and B are given. Both


variables contain real numeric values. If the value of A is
greater than 17 and less than 47, swap the values of A
and B, but if the value of A is either 5 or 87, increase
the value of A by 20 and decrease the value of B by 5.

Hint: Make use of a intermediate variable if it is


necessary to swap the values.

Example 6
The next example illustrates the use of a Boolean
variable.
Problem

A student wants to work out at the Keep Fit Gym. The


daily entrance fee is R8 for a member and R12 for a
non-member. The user has to enter the student’s name
and whether the student is a member. Display the
student’s name and entrance fee.

Planning

Table 19: Input and output variables for Example 6


Description Type Variable name

Input Membership status Boolean member

Student name String stName

Output Student name String stName

Message String message

Table 20: IPO chart for Example 6


Input Processing Output

stName Prompt to read input stName


values

age Enter input values message

Prepare message

Display output values


Algorithm

Test the program by setting the member to


TRUE after entering the name Sally Jones. Test
the program again by setting the member to
FALSE after entering the name Billy Ceronio.
Output:
Enter student name: Sally Jones

Indicate if the student is a member or not: TRUE

Sally Jones, you must pay R8 entrance fee.

Enter student name: Billy Ceronio

Indicate if the student is a member or not:


FALSE

Billy Ceronio you must pay R12 entrance fee


6 Data validation
It is a good programming technique to code defensively,
which means that you try to detect and identify all
errors that a user could possibly make. Users are often
inexperienced so many computer errors are actually a
result of incorrect user input. If a program can detect an
error before processing, the information will be
accurate and reliable.

There are a number of data validation tests that a


programmer can use to code defensively. At this point,
we’ll only test whether a numeric field contains a
numeric value before it can be used for processing. In
other words, the program will not be able to do
calculations if the variable does not contain a numeric
value.

Example of a numeric test

Exercises
1. Study the following problem statements carefully.
In each case, indicate the variables used, draw
an IPO chart and write an algorithm to solve the
problem. Do a trace table for every odd-
numbered question using carefully selected test
data.
1.1. Enter the annual salary of an employee and
also indicate whether the employee is a full-time
or part-time employee. Full-time employees pay
29.5% income tax whereas the other employees
pay 25% income tax. Calculate and display the
gross monthly salary, monthly tax payable and
the net monthly salary.
1.2. The Cheap Store sells affordable items to
customers. Provide the selling price, number of
items bought and discount percentage. The
discount only applies if a customer buys 10 items
or more. Calculate and display the discount and
the amount due by the customer.
1.3. An employee earns a basic salary of R1,200
per month. He also earns commission on sales.
The sales amount must be entered. On a sales
amount of less than R3,500 he receives 8%
commission, but if he sells more, the commission
is 12.8%. The employee pays 5% of his
commission to his manager. Calculate and
display his net income on the screen of the
computer.
1.4. Enter the distance that a participant in a
competition cycles as well as the distance the
participant swims. To earn a medal in a
competition, a participant must cycle at least 20
kilometres and swim 500 metres. Develop an
algorithm to determine if July qualified for a
medal.
1.5. Billy has to transport a number of computers
to his company. He can only load a certain
number, which must be entered, into his vehicle.
Enter the number of computers he has to
transport and, if this number is higher than the
number he can transport at the time he buys the
computers, display an appropriate message on
the screen. Also display how many computers
still need to be transported.
2. Write down only the exact output that will be
displayed after the following statements are
processed.
Hint: Use a table to enter the different values of
the variables after execution of statements to
determine the output.
3. In each of the following cases, indicate whether
the if statement is valid. If invalid, provide a
reason and rewrite it as a valid statement.
3.1. if empName = Jones then
3.2. if 12000 < empSalary < 20000 then
3.3. if newSalary > or = 25000 then
3.4. if salIncrease > 12% of Salary then
3.5. if number NOT = 20 then
3.6. if number NOT > 20 then
3.7. if number < 10 AND number > 20 then
3.8. if number < 10 OR > 20 then
3.9. if indication = True then
3.10. if number < 25 000 then
4. Rewrite each of the following statements in a
different way.
4.1. if numberA > numberB AND numberC = 10
then
numberD = number + 1
endif
4.2. if number >= 10 then
number = number + 1
endif
Chapter 5 The selection
control structure: Part 2

Introduction
Up to this point we′ve tested only one
condition in an if statement and we′ve
tested more than one condition in a
compound if statement, but it is often
necessary to test more conditions.
This chapter deals with more
complicated decision structures.

Outcomes
When you have studied this chapter, you should be able
to:
write a nested if statement in pseudocode,
write a select case statement in pseudocode,
write algorithms containing
• nested if statements, and
• select case statements.

1 Nested If statements
Study the following if-then-else statement:

Statement1 and/or statement2 could also be if-then-


else statements, depending on the problem statement,
which would change the general format to a nested if
statement, as follows:

Note the indentation in the nested if statement.


A nested selection structure is used if more than one
decision must be made before an appropriate action
can be taken. In the example above, condition1 is the
outer selection structure and condition2 and condition3
the inner selection structures. The inner selection
structures can also be nested.

The following examples are used to illustrate nested if


statements without logical operators (AND and/or OR).
Example 1
The gender of a person is indicated by the code M
(male) or F (female). In a competition, initial points are
awarded to each candidate. Every male older than 15
receives 17 points, whereas males younger than 16
receive 20 points. A female younger than 18 receives
18 points, whereas a female older than 17 receives 21
points.

After the first else clause, there is no need to test if the


age of the male is less than or equal to 15. This will
automatically be implied by the else clause and the
points can be set to 20 - there is no need to test for the
condition again. The same rule (logic) applies to the
second part of the if statement where the age for a
female is tested.
Example 2
Table 1 contains the values of the real variables A and
B and the steps to take when different conditions apply.

Table 1: Correspondences between A and B


Value of Value of B Steps to take
A

5.2 Greater than 20 Increase the value of A by 5

5.2 Less than or equal to Decrease the value of B by


20 3.5

6 Any value Initialise the values of A and B

Note
To initialise a value means assigning a zero to numeric
values and spaces to non-numeric values.
Note that if the value is not equal to 5.2 or is not equal
to 6, the values of A and B will not change.

Let′s start testing the algorithm with A = 5.2 and B = 25


as test data.

Table 2: Test 1
Instruction A B Outcome of if

Assign 5.2 25

If A = 5.2 True

If B > 20 True

Calculate 10.2

In Test 1, the value for A changed to 10.2, but the value


of B remained 25.

Now let′s test the algorithm with A = 5.2 and B = 15 as


test data.

Table 3: Test 2
Instruction A B Outcome of if

Assign 5.2 15

If A = 5.2 True

If B > 20 False
Calculate 11.5

In Test 2, the value for B changed to 11.5, but the value


of A remained as 5.2.

Now let′s test the algorithm with A = 6 and B = 100 as


test data.

Table 4: Test 3
Instruction A B Outcome of if

Assign 6 100

If A = 5.2 False

If A = 6 True

Assign 0

Assign 0

In Test 3, the value for A and B both changed to 0.

Finally, let′s test the algorithm with A = 8.3 and B = 21


as test data.

Table 5: Test 4
Instruction A B Outcome of if

Assign 8.3 21
If A = 5.2 False

If A = 6 False

In Test 4, the value for A will remain 8.3 and the value
of B 21.

Example 3
The variables A, B, K and Z are integers.

Table 6: Conditions to be met in order to take


action
Value of A Value of B Steps to take

0 - 14 0 -12 Double the value of K

15 - 21 0 -12 Swap the values of A and B

22 - 40 13 or more Decrease the value of K by 5


Once more, notice that the indentation enhances the
readability of the nested if statement. The final endif is
written in the same column as its associated if.

1.1 Nested If statements in


programs

Example 4
The Bright Light Company is increasing the salaries of
its employees according to which department they work
in, as shown in Table 7.
Table 7: Percentage increases by department
Department code Percentage increase

A 7.2

B 6.8

All others 6.3

The user has to enter the department code and the


current annual salary of the employee. The increased
monthly salary is calculated and displayed using a
nested if statement without logical operators. Data
validation applies.

Planning
Table 8: Input and output variables for Example 4
Description Type Variable name

Input Department code Character deptCode

Annual salary Real anSalary

Output New monthly salary Real monSalary

Table 9: IPO chart for Example 4


Input Processing Output

deptCode Prompt to read input values monSalary


anSalary Enter input values

Calculate monthly salary

Display monSalary

Algorithm

Test the program four times, to cover every


outcome of the if statement:
Department code = A Annual salary = R24000

Department code = B Annual salary = R38500

Department code = G Annual salary = R30000

Department code = C Annual salary = R5OOOO

When testing the algorithm, we have to include


incorrect data as well. In the last example, Os
instead of zeros will cause an error.

Output:
Provide the department code: A

Provide annual salary: 24000

The increased monthly salary is R2144.00

Provide the department code: B

Provide annual salary: 38500

The increased monthly salary is R3426.50

Provide the department code: G

Provide annual salary: 30000

The increased monthly salary is R2657.50

Provide the department code: C

Provide annual salary: 5OOOO

The annual salary must be numeric.


Example 5
A vet prescribes medicine for dogs to keep them
healthy and strong. The daily dosage depends on the
weight of the dog and is calculated according to the
following table:

Table 10: Dosage per weight


Weight of dog in kg Millilitres per 500 g

<5 1.0

5–8 0.9

> 8 – 12 0.75

> 12 0.6

The user must enter the name of the dog and the
weight of the dog in kilograms (to the nearest 500 g).
Then the algorithm must calculate and display the daily
dosage to be administered to the dog, as well as the
dog′s name.

Planning
Table 11: Input and output variables for Example 5
Description Type Variable name

Input Name of dog String name


Weight of dog Real dogWeight

Intermediate Variable used to test/calc Real number500

Output Name of dog String name

Daily medicine Real medicine

Table 12: IPO chart for Example 5


Input Processing Output

name Prompt for input values name

dogWeight Enter input values medicine

Calculate dosage

Display name, medicine

Algorithm
Comment 1
Each of the if statements tested only one condition, for
example, the second if statement:

if weight <= 8 then

It didn′t test if weight >= 5 AND weight <= 8, because


weight was already compared to 5 in the first if
statement. When control is passed to the else part of
that if statement, the weight is definitely greater or
equal to 5!

Comment 2
Similarly, it′s not necessary to test if weight > 8 AND
weight <= 12. In the last inner if statement it′s only
necessary to test if weight <= 12 because it will already
be greater than 8 when it reaches this part of the if
statement.

When testing this program, it′s important to use test


data that tests all the borderline cases to ensure that
the program produces correct output in all cases. It′s
also necessary to test the program with incorrect input
data to check that appropriate error messages are
displayed.
Test the program as follows:

Name of dog: Any name

Test weights: 3.5, 5, 8, 12 and 25.5 kg

Then test the program with weights 1O (O instead of 0)


and 10.8.

Finally test the program by omitting the dog′s name.

Output:
Provide the name of the dog: Fluffy

Provide the weight of dog in kg (to nearest 500


g): 3.5

Fluffy must receive a daily dose of 7.0 ml

Provide the name of the dog: Daisy

Provide the weight of dog in kg (to nearest 500


g): 5

Daisy must receive a daily dose of 9.0 ml

Provide the name for the dog: Georgy Girl

Provide the weight of dog in kg (to nearest 500


g): 8

Georgy Girl must receive a daily dose of 14.4 ml


Provide the name for the dog: Danny Boy

Provide the weight of dog in kg (to nearest 500


g): 12

Danny Boy must receive a daily dose of 18.0 ml

Provide the name for the dog: Victor

Provide the weight of dog in kg (to nearest 500


g): 25.5

Victor must receive a daily dose of 30.6 ml

Provide the name for the dog: Lady

Provide the weight of dog in kg (to nearest 500


g): 1O

The weight entered for Lady must be numeric.

Provide the name for the dog: Tinky

Provide the weight of dog in kg (to nearest 500


g): 3.8

The weight must be in kg and to the nearest 500


g, e.g. 3, 3.5 or 4.

Provide the name for the dog:

The name of the dog must be entered

Example 6
The price of hiring a car per day from the Reliable Car
Hire Company depends on the type of car the customer
hires. The customer may choose between small (S),
medium (M) and large (L) cars as shown in Table 13.

Table 13: Car rental pricelist


Type of car Daily price in Rand

S 200

M 260

L 400

The user is asked to enter the type of car he or she


needs as well as the number of days it will be hired.
Calculate and display the total amount the customer has
to pay, using a nested if statement. At the moment,
there is a special offer of a 12.5% discount for hiring a
small car.

Planning
Table 14: Input and output variables for Example 6
Description Type Variable name

Input Type of car Character code

Number of days Integer noDay

Output Amount due Real amtDue


Table 15: IPO chart for Example 6
Input Processing Output

code Prompt for input values amtDue

noDays Enter input values

Validate data

Calculate amtDue

Display amtDue

Algorithm
In addition to testing a normal transaction, we
should test incorrect data. We′ll include a non-
existent car type as well as a non-numeric value
for the number of days. We′ll also include a
small car to test the special offer.

Test the program as follows:

Type of car Number of days

Small 4

Large 3

Grand 9

Medium K

Output:
Enter the type of car you need S, M or L: S

Enter number of days for car hire: 4

The amount due is R700.00

Enter the type of car you need S, M or L: L

Enter number of days for car hire: 3

The amount due is R1200.00

Enter the type of car you need S, M or L: G

Enter number of days for car hire: 9

Wrong code entered, only S, M or L is valid. You


entered the code G

Enter the type of car you need S, M or L: M


Enter number of days for car hire: K

Number of days entered not numeric. You


entered K

Exercises
1. Write only the nested if statements without
logical operators for each of the following
problem statements. You can assume that all the
variables contain valid values. Choose your own
variable names where applicable.
1.1. Calculate the medical aid contribution of an
employee calculated according to the values in
Table 16. You can assume that the salary is
stored in the variable called salary and the
number of dependants is stored in the variable
noDepend.

Table 16: Medical aid contributions


Monthly salary Dependants Percentage of salary

0 – 4999.99 Any number 2%

5000 and more 0 1 or more 4% 3.5%

1.2. If the ABC field contains a negative value,


calculate the value of XYZ by multiplying the
value of ABC by 2.5, but if the value of ABC is
positive, store 35% of ABC in XYZ. If the value
of ABC is zero, decrease the current value of
XYZ by 8.3%.
1.3. The variable called person contains code A
for adults or C for children, whereas the variable
called member contains True or False to indicate
whether the person is a member of the club. The
club is having a fun day and the entrance fee is
determined as follows: R25 for adult members
and R8 for child members. A non-member pays
50% more than a member. Store the entrance
fee in a variable called fee.
1.4. At the Cheap-Unfair Company, salaries of
employees are computed as follows:
• A male employee earns a basic salary of
R7000 per month. He receives an additional
R150 for each year of service, and an
additional R550 if he has a qualification. A
10% tax and 7% pension fund contribution are
deducted from his gross salary to determine
his net salary.

• A female employee earns a basic salary of


R6500 per month, an additional R140 for
every year of service and an additional R650
if she has a qualification. An 8.5% tax and
7.5% pension fund contribution are deducted
from her gross salary to determine her net
salary.
The user must provide the necessary input values
and must use a logical (Boolean) value for the
qualification.
1.5. At the ABC Company, employees are paid a
certain rate per hour. The company wants to
modify the rate as follows:
• If the number of hours worked (hours) is 40
and the rate per hour (rate) is less than
R28.50, increase the rate per hour by R1.50.

• If the number of hours is 40 and the rate per


hour is R28.50 or more, increase the rate per
hour by R1.20.

• If the number of hours worked is greater


than 40 and the rate per hour is greater than
or equal to R28.50, increase the rate per hour
by 1.5%.

• If the number of hours is less than 40,


decrease the rate per hour by R0.50 per
hour.

After the rate has been modified, calculate the


pay.
2. Study the following algorithm and predict the
answers when the variable called code is equal
to 4, 9 or 2. In all three cases, the variable called
amount is equal to 1000.
3. Study the following nested if statement, then
complete the third column (the value for z) if the
values for x and y in Table 17 are used.

Table 17: Values of x and y


x y z

5 8

-5 -6

-3 -3

10 5

4. Carefully study the following problem statements.


In each case, indicate the variables used, draw
an IPO chart and write an algorithm to solve the
problem. Create a trace table for every odd-
numbered question using carefully selected test
data.
4.1. Poppy, who counts every cent to get the
best value for her money, needs to buy washing
powder. She went to the shop and wrote down
the prices of the 500 g, 750 g and 1 kg packets
of her favourite washing powder. She wants to
write a program to determine which one of the
packets is the best buy (most economical). Do
the calculations and display which packet she
should buy. The user should be prompted to
enter the prices for all three packets.
You can test your program with the following test
data:
500 g R14.85

750 g R21.95
1kg R29.83

Don′t use these values as fixed values in your


program – use them only as test values.
4.2. Johnny has some money saved in the bank
on which he earns an annual interest of 9.5%.
Johnny needs to enter the amount he has saved,
then calculate the amount of interest he earns
every month. For the sake of the calculation you
can assume that an equal amount of interest is
earned every month (disregarding the varying
number of days per month). Calculate and
display the income tax he has to pay on the
interest earned according to the values in Table
18.

Table 18: Income tax on interest earned


Interest amount Percentage income tax payable

Less than R1000 0

R1000.01 – R2000 7.5% on amount > R1000

R2000.01 – R3200 9.5% on amount > R1100

4.3. The Anything Company employs


representatives who sell products to the public.
These representatives (code = REP) are
grouped into areas. Each area has an area
manager (code = AM). A region contains five
areas and has a regional manager (code = RM).
Each representative receives a 20% commission
on sales, whereas his/her area manager receives
5% on it and the regional manager receives 2%
on it. Area managers and regional managers may
also sell products.
Therefore:
• If the representative sells the products,
he/she gets commission (20%), the area
manager gets commission (5%) and the
regional manager gets an amount (2%),

• If the area manager sells the products,


he/she gets commission (20% + 5%) as well
as the regional manager, who gets 2%,

• If the regional manager sells the products,


he/she gets all the commission (20% + 5% +
2%).

The user enters a representative′s name, code


and amount of sales. Provide for incorrect input
values. Depending on the code, calculate and
display the commission for each person.
Examples:
• Code REP – display the commission for the
representative, area manager and regional
manager,

• Code AM – display the commission for the


area manager and regional manager,

• Code RM – display the commission for the


regional manager.

2 The Select Case structure


Like nested if statements, select case structures are
used to perform processing steps depending on the
outcome of a tested condition. However, case
structures are used when the same variable is tested
for many different values.

Study the following if statement:

The same condition can be tested in a select case


statement, which is much easier to read.
This structure always begins with the words ‘select
case′ and ends with ‘endselect′. Note the indentation to
ensure that the code is easier to read and understand.
The ‘case else′, which is used when none of the options
is true, is optional, not mandatory.

There can also be more than one statement for an


outcome of a specific condition.

In the following example, different ranges of values of


noItems (number of items) are tested to assign a
percentage and display a specific code, then to
calculate a discounted amount and display the answer.
Example 7
Write a select case statement to calculate the new
value of the price variable depending on the grade,
based on the values in Table 19.

Table 19: Price according to grade


Grade Processing of price

A Double the price

B Add VAT of 14%

C Deduct a discount of 8.75%

Other Add R5 if the price is higher than R50


Subtract R4 if the price is equal to R50 or lower
Example 8
The following example demonstrates that it is not
necessary to test each value that has the same
outcomes in separate case statements.

Write a select case statement for the following: If the


name is Sally or Tania, display the message “She is a
girl.”; but if the name is Jim, John or Russell, display the
message “He is a boy.”
Example 9
Summer has to read a number of prescribed books and
has decided to reward herself by watching TV for an
allocated number of minutes based on the number of
pages she reads. Enter the number of pages read, then
calculate and display the minutes using a select case
statement. If more than 400 pages are entered, an
error message must be displayed, because none of the
prescribed books has that many pages!

Table 20: Minutes per number of pages


Pages read Minutes

0 – 20 0

21 – 50 10

51 – 100 40

More than 100 75

Planning
Table 21: Input and output variables for Example 9
Description Type Variable name

Input Number of pages Integer pages

Output Number of minutes Integer minutes


Error message String message

Table 22: IPO chart for Example 9


Input Processing Output

pages Prompt for pages minutes

Enter pages message

Calculate minutes

Display minutes and message

Algorithm
Test data: Pages = 45, 432, -6, 255, 16

Output:
Enter the number of pages read: 45
Good girl! You may watch TV for 10 minutes.

Enter the number of pages read: 432

The pages must be > 0 and not more than 400.

Enter the number of pages read: -6

The pages must be > 0 and not more than 400.

Enter the number of pages read: 255

Good girl! You may watch TV for 75 minutes

Enter the number of pages read: 16

You must read more than 20 pages to watch TV.


Better luck next time.

Exercises
1. Write only the select case statements for the
following problem statements.
1.1. If the value of K is equal to 3, increase the
value of A by 5%. If the value of K is equal to 4,
decrease the value of A by 8. If the value of K is
equal to 7, add the value of B to the value of A,
otherwise decrease the value of A by 12%.
1.2. If the integer variable called xyz contains a
value of 3, 8 or 9, display three asterisks, but if
xyz contains a negative value, display five
asterisks. However, if the value is between 10
and 20, then display seven asterisks. If xyz
contains any other value, display four equals
signs.
1.3. Change the value of the variable called X
based on the value of A, as given in Table 23. A
and X contain positive values; X is a variable with
a real value and A is variable with an integer
value.

Table 23: Actions to be taken regarding X,


depending on the value of A
Value of A Value of X

Less than 15 Increase by 2.5%

Between 20 and 30 Replace with the square root of


X

Greater than or equal to Decrease by 12.5%


50

None of the above Increase by 10% of A

1.4. The marital code of a person is stored in the


variable called marCode. Display the
corresponding description on the screen. Provide
for an incorrect marital code.
s = single M = married

D = divorced W = widowed

1.5. The commission that a salesperson earns is


stored in the variable called income. The
salesperson also earns a bonus, based on the
sales that are stored in the variable called sales,
as given in Table 24.

Table 24: Bonus sliding scale


Sales in Rand Bonus in Rand

0 - 5 000 0

5 001 - 10 000 500

10 001 - 35 000 1 500 + 0.5% of sales

35 001 and more 4 000 + 1% of sales

2. Display the bonus using a select case statement.


2.1. Rewrite the following if statement as a
select case statement.
2.2. Rewrite the select case statements in
Examples 7 and 8 as nested if statements.
3. Study the following problem statements carefully.
In each case, indicate the variables used, draw
an IPO chart and write an algorithm to solve the
problem.
3.1. Rewrite the nested if statement you wrote in
Section 1, Exercise 4.2 as a select case
statement.
3.2. Enock runs a gardening service that charges
by the hour on a sliding scale, as given in Table
25. He also charges an additional R2.50 per hour
for equipment used. Enter the hours worked as a
real number and calculate and display the amount
owed to him. Use a select case statement to
calculate the amount.

Table 25: Hourly rate sliding scale


Hours worked Payment per hour

0–2 R20.00

>2 – 4.54 R19.20

4.6 – less than 6 R18.20

6 hours and more R17.88

3.3. The cost of postage depends on the weight


of a parcel. The weight is entered in kilograms. If
the parcel weighs 1.5 kg or less, the postage is
R15.85. Postage increases at a rate of R7.50
per kilogram or part thereof, if the weight is more
than 1.5 kilograms. Calculate the postage for a
parcel and display the postage and weight on the
screen.
3.4. Enter an integer value for the variable called
num that contains a value between 35 and 74.
Determine if the ‘tens′ digit is equal to, greater
than or less than the ‘ones′ digit and display the
number and a message accordingly. Choose
appropriate variable names.
Output examples:
The number is 47
The tens digit is less than the ones digit
The number is 55
The tens digit is equal to the ones digit
The number is 63
The tens digit is greater than the ones digit
3.5. Enter an integer value for the variable called
num that has a value between 14 and 50.
Determine if the number is a multiple of 3 and if
not, determine if the number is a multiple of 17.
Display the number and a suitable message.
3.6. Employees working at the Good Fortune
Company have the option of joining a savings
plan. There are three plans available − Premium,
Gold and Silver. The name of the employee, the
salary and the name of the selected plan are
entered. The company deducts 8% of an
employee′s salary for the Premium savings plan,
5% for the Gold plan, and R150 for the Silver
plan. Determine the amount that must be paid to
the savings plan. If an incorrect plan name is
entered, the amount paid to the savings plan is
zero. The amount that has been saved to date
must also be entered, and must be increased by
the new amount. Display the name of the
employee and the total amount saved. Use a
select case statement to determine the plan
selected.
3.7. FRIENDLY CONSUMER is an application
that gives advice about various products to
consumers. The user must enter the description
of a product as well as the current price and the
price one year ago. The algorithm must then
evaluate whether the current price is less than,
equal to or greater than the price one year ago.
If greater than (which is more than likely), the
difference between these two prices must be
calculated. The algorithm must display a
message advising the user to buy a product only
if the price remained the same or decreased
(which is unlikely).
If there was an increase in the price, the
algorithm must calculate the percentage increase
and compare it with the current rate of inflation of
6.3%. If the increase percentage is less than or
equal to the inflation rate, the user must be
advised to buy the product. However, users must
be advised not to buy a product if the price rose
more than the inflation rate.
3.8. At the ABC cellphone company, the price of
a phone call using an ABC cellphone depends on
the length of the call and the connection type, as
given in Table 26. Type A clients get a 10%
discount on all calls.

Table 26: ABC cellphone tariffs


Connection type Price in R/c per minute or part thereof

An ABC cellphone .90

Other cellphone 1.35


Landline 1.90

The user must enter his/her cellphone number


and the length of the call in seconds. The user
must then enter the connection code − 1: ABC
cellphone; 2: Other cellphone; 3: Landline – as
well as whether the client is a type A client
(TypeA = “Y” or “N”).
The amount due must then be calculated and
displayed. Use if statements for the calculations.
You can assume that all input will be correct.
3.9. The HELP-A-STUDENT scheme provides
loans to students to complete their studies. At
the end of their studies simple interest of 15% is
added to this amount to determine the total
amount that must be paid back. However, if a
student obtains two or more distinctions over the
total study period, discounts apply as follows:
for 2 – 3 distinctions, 3.5% is deducted from the
total amount;
for 4 – 5 distinctions, 5.5% is deducted from the
total amount;
for 6 – 8 distinctions, 7.5% is deducted from the
total amount and
for more than 8 distinctions 10% is deducted
from the total amount.
This total amount must then be paid back in equal
payments over 1½ times the number of months
that the amount was borrowed.
Enter the required values, then calculate and
display the following:
• total amount that will have to be paid back,

• number of months over which it must be


paid back, and

• the monthly instalment.

3.10. Lerato wants to bake a chocolate pudding


that makes its own sauce. She has two baking
dishes available, but to prevent the pudding from
boiling over, she wants to bake it in the baking
dish with the larger volume. One baking dish is
round and the other is square. Enter the diameter
and the depth of the round baking dish, then
enter the length and depth of the square baking
dish. Calculate the volume of both baking dishes.
Based on the outcome, display a message to
indicate which baking dish to use for the pudding.
If the volume of both is the same, display a
message to indicate that either of the two can be
used. The volume of both baking dishes must
also be displayed as output. You can assume
that all input values entered will be valid.
You can use the following formulas in your
solution:
Volume of round baking dish = πr2d(π=3.14285,
r = radius,
d = depth)
Volume of square baking dish = 2ld (l = length, d
= depth)
4. 4.1. Rewrite the following if statement in a more
efficient way.

4.2. Identify the mistake in the following if


statement.
5. Write down the exact output of each of the
following groups of statements.
5.1.

5.2.

5.3
5.4.
Chapter 6 Iteration using a
fixed count loop

Introduction
Programming often involves repeating
a set of instructions a number of times.
Sometimes we know exactly how many
times we need to repeat the
instructions, and other times we don’t.
This type of programming is called
iteration or looping. In this chapter,
we’ll discuss the for loop where we
know exactly how many times to
repeat a set of instructions. This is
sometimes called a fixed count loop
or an automatic count loop.

Outcomes
When you have studied this chapter, you should be able
to:
write a loop in pseudocode using a for-next
statement,
explain the purpose of an accumulator and
implement it in a solution, and
know when to display output during every
execution of a loop and when to display it at
the end of the loop.

1 The For-next loop


The syntax of the for-next loop is as follows:

Variable1 indicates a variable that contains the initial


value or begin-value. The statements in the body of the
loop will then be executed, after which variable1 will be
incremented by variable2. This process will continue
until variable1 has moved past end-value for the first
time. Variable1 is called the index of the for-next loop.

If [step variable2]is omitted, a default value of +1 is


used.
There can be one or many statements in the body of
the for-next statement.

If the step is negative, begin-value must be greater than


end-value.

It is not necessary that the variables must be integers.


The step may be a fraction, in which case all variables
must be of the data type real.

Example 1
A for-next statement is used to display the consecutive
numbers from 1 to 10.

The output will be:

1 2 3 4 5 6 7 8 9 10

Note the space (“ “) in the display statement, which


ensures that the output is more readable.

This for-next statement can be written more effectively


using the index i, as follows:
These statements will produce the same result.
Figure 1 Flowchart of the For-next statement using
an index
Example 2
The for-next statement is changed to display the
consecutive numbers from 1 to 10 in descending order.
This means that the step must be negative and the
statements must change, as follows:

The output will now be:

10 9 8 7 6 5 4 3 2 1
Figure 2 Flowchart of the For-next statement with a
negative step
Questions
What will the output of the following for-next loops be?

Example 3
The sum of the first five odd numbers is calculated and
displayed.

People often think that they don’t need the sum until just
before the processing ends, so they plan to calculate
the sum just before it’s needed. But it simply doesn’t
work that way!
Right at the end, only the last odd number is available.
So whenever the number – in this case, the next odd
number – is available, it must be added to the sum.
Every number will be available in the current execution
of the loop.

Let’s create a trace table to make this clearer.

Table 1: The trace table for Example 3


Instruction sum odd k Output

assignment 0

assignment 1

for 1

calculation 1

calculation 3

for 2

calculation 4

calculation 5

for 3

calculation 9

calculation 7

for 4
calculation 16

calculation 9

for 5

calculation 25

calculation 11

for 6

display The sum of the first 5 odd numbers


is 25

Note that in this example, the answer is only displayed


once, after the loop has terminated.

The technique used above, to add or summate inside a


loop, is sometimes referred to as accumulation. The
variable, sum, is called an accumulator. Accumulation
is often used in problem solving to calculate a total or
an average. When you add 1 to the accumulator during
every execution of the loop, the accumulator is called a
counter.
Figure 3 Flowchart representation of Example 3

Example 4
The first six multiples of 5 (starting at 5) are displayed,
as well as their sum.

Once again, we need the sum of all the numbers at the


end of the execution of the loop. However, we can only
calculate the sum if we add every number (multiple of 5)
to the sum when it becomes available during each
execution of the loop.

The sum must be displayed only once, at the end of the


loop. However, we need to display every new multiple
of 5 before we add it to the sum, as stated in the
problem statement. So we also need a display
statement inside the loop. We can display it just after
we’ve added it to the sum, as long as we display it
before the next multiple of 5 is calculated.

The loop will have to execute six times because we


need to calculate six multiples of 5.

Algorithm
Next we’ll test the algorithm using a trace table.

Table 2: The trace table for Example 4


Note that each multiple of 5 is displayed in the loop and
their sum is only displayed once, after the loop has
terminated.

Example 5
Eight integers between 5 and 48 are entered and the
average of these numbers is displayed.

Before we start doing the algorithm, we first have to


think about it, make some notes and plan how we’re
going to do the logic.

Once more, we only need the average right at the


end, but we need a sum before the average can be
calculated. To calculate the average, we also need
the value of the final sum to be divided by the
number of values added to the sum. This can only
be done after the loop has terminated and before
the program terminates.
The eight numbers must be entered one by one by
the user within the for-next loop, and added to the
sum.
Each number entered must be validated first to
check that it is indeed between 5 and 48. If not, an
error message must be displayed and the user must
re-enter it. Because the loop is executed eight
times, 1 will have to be deducted from the counter
that controls the loop to repeat that execution of the
loop.
Finally, the average can only be displayed after it
has been calculated just before the final display
statement.

Algorithm

Let’s look at some more worked examples that


use loops.

Example 6
This example shows the planning and an algorithm to
display a series of even numbers. These two questions
must be asked of the user:
At what even number do you want to start?
How many even numbers do you want to display?

Planning
Table 3: Input and output variables for Example 6
Description Type Variable name

Input Even number to start Integer beginNo

How many even numbers Integer howMany

Output Output even numbers Integer evenNo

Table 4: IPO chart for Example 6


Input Processing Output

beginNo Prompt for input values evenNo

howMany Enter input values

Calculate new even number

Display evenNo

Algorithm
Test the logic with the following four sets of test data:

beginNo = 8, howMany = 10

beginNo = 9, howMany = 15

beginNo = 16, howMany = -3

beginNo = x, howMany = 3
Output:
8 10 12 14 16 18 20 22 24 26

The begin number must be an even number

The number must be numeric and greater than 0

The begin number must be numeric

Questions
1. What will the output be if the user enters -16 as
the begin value and 9 for howMany?
2. What will the output be if the user enters 0 as the
begin value and 4 for howMany?

Exercises
The for-next statement in the DisplayEvenNumbers
algorithm can be changed as follows:

Create a trace table to prove that this last for loop will
yield the correct result.

Example 7
The ten students in the Information Systems class at
Brilliant College wrote a test. The principal of the
college wants to know what the highest mark is and
who obtained it, as well as the name and mark of the
student who obtained the lowest mark. The user must
enter all the names and test marks, which must be
displayed. The marks are percentages given as
integers. Assume that none of the students have the
same mark.

Planning
When planning this program, we need to clarify a few
aspects. First we need to have a value to compare the
current mark to, to determine which mark is lower or
higher than the other one. So we’ll declare one variable
called lowest and another called highest. These will
contain the lowest and the highest test marks
respectively.

There are two ways to do this:

Method 1

Assign a very low value to highest (-1 for instance)


so that all the current values compared to this
number will be higher.
Then assign a very high value to lowest (101, for
instance) so that all the current values compared to
this number will be lower.
Then repeat the process ten times.

Method 2

Assign the mark of the first student to both lowest


and highest in order to compare the current values.
Repeat the process only nine times, because the
first value has already been dealt with.

We’re going to use the second method in our algorithm.


We’ll also assume that all input values will be valid.

Table 5: Input and output variables for Example 7


Description Type Variable name

Input Name of student String stName

Student’s test percentage Integer testMark

Intermediate Student number Integer st

Output Name of best student String highestName

Highest percentage Integer highest

Name of weakest student String lowestName

Lowest percentage Integer lowest

Table 6: IPO chart for Example 7


Input Processing Output

stName Prompt for input values highestName

testMark Enter input values highest

Compare to find results lowestName

Display output values lowest

Algorithm
Test the logic using this test data.

Name: Danny Test percentage: 50

Bill 67

Don 92

Dave 28

Sonny 62

Edith 54

Bob 34

Robbie 43

Cassandra 64

Julie 78

Output:
The name of the student who obtained the
highest mark is Don

The highest mark obtained is 92

The name of the student who obtained the


lowest mark is Dave

The lowest mark obtained is 28


Example 8
In this program we’re going to do division by subtracting
values using a for-next loop.

The user is asked to enter an integer total number that


is greater than 400. The result will be calculated by
dividing the total number by 5 without using division. The
answer must be an integer and the remainder, if any,
must be discarded.

Planning
Table 7: Input and output variables for Example 8
Description Type Variable name

Input Total number Integer totNumber

Output Result Integer result

Table 8: IPO chart for Example 8


Input Processing Output

totNumber Prompt for totNumber result

Enter totNumber

Subtract 5 from totNumber until finished

Display result
Algorithm

Test the logic using 543 and then 3, followed by


x as the total number.

Output:
The number can be divided by five 108 times

The number must be greater than 400

The number entered must be an integer


Exercises
Do the planning and write algorithms to solve the
following problems:

1. The user wants to display a message a fixed


number of times. Ask the user to enter the
message and the number of times it must be
displayed. Display the message the required
number of times.
2. The price of an item was R100 in 2007. If the
rate of inflation is 6.5% per annum, calculate and
print each year since 2007 with the price of the
item in that year, up to and including 2020.
3. ;Jenny goes shopping and buys five different
items. She is asked to enter the prices of each
item within a loop and to calculate the amount
due. Add 14% VAT to the total that must be
displayed.
4. The distribution manager of a newspaper uses
25 youths to help her deliver the newspapers
early in the morning. She has to know the
average number of newspapers delivered by one
youth, as well as how many youths deliver more
than the average, how many deliver less than the
average and how many deliver the average
number. Use a for-next loop to enter the number
delivered by each youth. Display the average, the
number exceeding the average, the number less
than the average and the number equal to the
average. Hint: Calculate the average using one
for-next loop, then use another for-next loop to
determine the totals.
5. The Direct Postal Service sends parcels to
customers all over the world. Customers
frequently request that items to be packed in
separate parcels. Each parcel is marked with the
name of the customer, the weight of the parcel
and the sequence number of the parcel. For
example, if five parcels are sent to the same
customer, the second parcel will be numbered 2
of 5. The user is asked to enter the name of the
customer and the number of parcels (maximum
20 parcels). This number is used to control the
for-next loop. The weight of every parcel (real
number) must also be entered before the details
for every parcel are displayed, as follows:
Name of customer

Weight of parcel in kg

Parcel x of y

Plan for only one customer.


6. A company that sells vacuum cleaners uses
representatives to sell their stock. Each
representative is given a goal by the company. If
the representative sells more vacuum cleaners
than the goal, he or she receives R56.20 as a
bonus per additional vacuum cleaner sold. If the
representative has not met the goal, he or she
has to pay R15.75 for every vacuum cleaner sold
less than the goal. Enter the name, goal and
number of vacuum cleaners sold, then calculate
the bonus or the amount that must be paid to the
company. Display the name and amount for each
representative. Repeat this procedure for 50
representatives.
7. There are 30 students in the Programming 1
class. The age of every student is entered in
years and months. Convert the age into months
to calculate the average age. Display the answer
(average age) in years and months on screen.
8. The user must enter a positive integer less than
or equal to 15. If this number is valid, the user
must also enter a choice of 1, 2 or 3, which must
result in the following output:
1. Display the first 5 multiples of the number
entered and the sum of these multiples
2. Display all consecutive positive numbers
up to this number
3. Display the factorial of this number
Display an appropriate error message only
if the choice or the positive integer number
is incorrect. Use a select case structure to
handle the choices.

Examples
Assume a 5 has been entered as a
positive integer number. The output may
be one of the following, depending on the
choice made.

Note
The factorial is the product of all
consecutive positive numbers up to this
number:
1 x 2 x 3 x 4 x 5 = 120

9. Write the algorithms to solve the following


problems:
9.1. Calculate and display the sum of the first 20
elements in the following series:
1; 2; 4; 7; 11; …
9.2. Display the value of the 30th element in the
following series on screen:
2400; 2398; 2394; 2388; 2380; ...
10. In each case, predict the output of the given
algorithm:
10.1

10.2

2 Nested For statements


In many situations, it is necessary to use a loop
contained within another loop.

Example 9
A structure like these loops is called a nested loop.

When the nested loops in the example are executed,


the values of the counters i and j will vary when
executed, as follows:

i j

1 1

1 2

1 3

2 1

2 2

2 3

If we apply these loops to students writing tests, there


would be two students (outer loop) who wrote three
tests each (inner loop). This idea will be further
illustrated in the next example.

It is clear that the inner loop will move through all the
counts before the index in the outer loop increments the
counter – and then the inner loop starts again from the
beginning.

Example 10
Four students in a class wrote three tests each. The
average of the three tests will provide the final mark for
the student. Display the final mark for each student as
well as the class average on the screen.

Planning
Table 9: Input and output variables for Example 10
Description Type Variable name

Input Test mark Integer tstMark

Intermediate Total sum Integer totSum

Sum Integer sum

Output Final mark Integer finMark

Class average Integer average

Table 10: IPO chart for Example 10


Input Processing Output

tstMark Prompt for input finMark

Enter tstMark average


Calculate finMark

Display finMark

Calculate average

Display average

Algorithm

You can test the logic with this test data:

Tests 1 2 3

Students 1 45 50 55
2 63 68 71

3 23 34 31

4 41 61 59

Draw a trace table to determine whether the


logic yields the correct result.

Exercises
1. Code an algorithm, using nested for-next loops,
to draw the following figure:

1
12
123
1234
12345
123456
1234567
12345678
123456789
You may display only one digit per statement and
may not repeat any of the statements – it must
be coded effectively!
Hint: The maximum for the counter in the inner
for-next loop must be the same as the current
counter in the outer for-next loop.
2. In each case, predict the output of the
pseudocode.
2.1.

2.2.

2.3.
2.4.

3. Do the planning and write an algorithm to solve


the following problem.
There are seven libraries, numbered 1 to 7, in the
city of Grandioso. Each library has eight sections
of books. Input the number of books for each
section in one library and accumulate the total
number of books in the library.
Hint: Use a nested for loop. Display the number
of the library with the most books and the
number of the library with the least books.
Chapter 7 Iteration using
the Do loop

Introduction
In the previous chapter, we discussed
the for-next loop, where the number of
times some statements had to be
repeated was known. However, the
exact number of times that a loop must
repeat is often not known. Therefore it
will be necessary to study other types
of loop structures as well.

Outcomes
When you have studied this chapter, you should be able
to:
understand the difference between a pre-test
and a post-test loop,
write a do-while loop in pseudocode,
write a do-loop-until statement in pseudocode,
describe a sentinel and use it to terminate a
do loop,
write algorithms containing
do-while loops,
do-loop-until statements, and
combinations of all structures learnt to date,
such as if statements within a loop.

1 The Do loop
To illustrate the concept of a loop that has an unknown
number of repetitions, or iterations, imagine a long
queue of people waiting to buy tickets for a football
match. If there are ten people in the queue, we might
say that the loop will be repeated ten times, however,
more people might join the queue so it isn’t clear how
many tickets will be sold.

Certain conditions may stop this process, for example:

All the available tickets have been sold.


The box office closed at 17:00.
All the people in the queue have already bought their
tickets.
The box office never opened.
If all these conditions were included in a solution, it is
clear that we really have no idea when the repetition
must stop. We need a statement to test these
conditions, otherwise the loop will run forever (endless
loop).

There are two types of do loop. When planning a


solution that contains a number of statements to be
repeated several times, the programmer has to decide
which type of loop must be used.

1.1 Pre-test loop (Do-while


statement)
The first type is called a pre-test loop where the
condition is tested before the statements within the loop
are processed. Looking at the box office selling football
tickets, we see that various conditions may occur: there
might not be a queue because no-one wants to buy
tickets, all the tickets might have been sold out
yesterday or the person who sells the tickets hasn’t
opened the box office. In this case, no tickets will be
sold.

Here’s an example of this type of loop, in which the


closing time of the box office is tested.
The statements in the body of the do-while loop will be
processed while the condition is true. As soon as it
becomes false, the statement after the end of the loop
will be processed. However, if the condition is false the
first time it’s tested, the statements in the loop might
not be executed at all.

The condition could also be a compound test. It could


happen that all the tickets are sold out before 17:00.
The condition in the code could then be changed, as
follows:

1.2 Post-test loop (Do-loop-


until statement)
The other type of do loop is called a post-test loop .
The statements in the body of the loop are processed
at least once, and the condition is tested only after the
statements in the body of the loop have been
processed. Consider a situation in which 100 tickets are
available but there are 150 people waiting to buy
tickets. So tickets can be sold only until all the tickets
have been sold and no more tickets are available.

Here’s an example of this type of loop, in which the


number of tickets is tested.

The statements in the do-until loop will be processed


repeatedly until the condition at the end of the loop
becomes true. Processing will then proceed to the
statement after the do loop structure.

1.3 Terminating execution of


a loop
There must be a statement in the body of a loop – in
both pre-test and post-test loops – that enables the
outcome of the condition tested in the loop control
statement to change. If this statement is absent, the
loop will never end.
Using our ticket sales example, the statement in bold
type could cause the loop to terminate.

Another method of terminating a loop is to use a


sentinel. Suppose sales must be entered repeatedly to
determine the highest sales. The programmer may
decide to enter a sales amount of -1 to end the loop.

Any suitable value could have been chosen to indicate


the end of the processing, as long as the value is not a
valid input to the program. This value is called a
sentinel.

For a pre-test loop, it is important to note that the


variable that controls the loop (in the next case the
variable called salesAmount) must receive an initial
value before the loop is entered for the first time. The
next value for this variable must be entered at the end
of the body of the loop, just before the next execution of
the loop.
1.4 Examples of Do-while
loops
As discussed before, this type of loop tests a condition
before processing the statements in the loop. So it’s
possible that the body of a do-while loop might never
execute.

Example 1
This example calculates the sum of all the consecutive
integers starting at 24 while the sum is less than 23456.
It then displays how many integers have been added to
the sum.
Once again, to yield the correct results, it is important
to understand which statements must be done before
processing the loop, which statements must be inside
the loop and which statements must be placed after the
loop.

Comment 1
These statements prepare the variables before entering
the loop. They initialise the variables with the correct
starting values.

In the do-while control statement, the sum is tested to


check that it is less than 23456. In the body of the do-
while loop, the statement sum = sum + number will
increase sum. Because number is a positive integer,
sum will increase until it eventually reaches 23456 or
more. At this stage the do-while loop will terminate. The
count is also incremented to indicate that the body of
the loop was processed once more.

Comment 2
It is only possible to print a final count when the
condition in the do-while control statement is no longer
met.

Example 2
Now we’re going to do all the planning for the following
problem.

The fishing society holds a competition to find out who


the best fisherman is. The competition is won by the
person who caught the most fish within a specified time.
For every fisherman, the name of the person and the
number of fish caught are entered. After all the data is
entered, a number of fish equal to -1 (sentinel) is
entered. The name of the winner and the number of fish
the winner caught are displayed on screen. For the
sake of this problem, we’ll assume that none of the
fishermen caught the same number of fish.

Planning
Table 1: Input and output variables for Example 2
Description Type Variable name
Input Name of fisherman String fmName

Number of fish caught Integer noFish

Output Most fish Integer winnerNumber

Name of winner String winner

Table 2: IPO chart for Example 2


Input Processing Output

fmName Prompt for input values winner

noFish Enter fmName and noFish winnerNumber

Determine winner

Display winner, winnerNumber

Algorithm
Before we start writing the algorithm we have to
plan the loop. The control statement in the do-
while loop has a condition, and when we read
the problem statement closely, it is clear that the
number of fish is tested in this condition. Once
the loop is entered, the condition must already
contain a value to be tested.

It’s clear that the number of fish caught by the


first person must be entered before the loop. But
there is no need to enter the name of the
fisherman before the loop is entered. This
implies that the number of fish caught by the next
person must be entered at the end of the body
of the loop to be tested when returning to the
do-while loop control statement.

This test data would cover all possible


conditions.
Name: Sam Number of fish: 8

Johnny 2

Kevin 7

Fred 10

Bill 5

Ted 12

Paul 9

Output:
Provide the number of fish caught by the first
fisherman

Enter -1 to indicate no more input 8

Provide name of fisherman Sam

Provide the number of fish caught by the next


fisherman

Enter -1 to indicate no more input 2

Provide name of fisherman Johnny

:
Provide the number of fish caught by the next
fisherman

Enter -1 to indicate no more input 9

Provide name of fisherman Paul

Provide the number of fish caught by the next


fisherman

Enter -1 to indicate no more input -1

The name of the winner is Ted

Ted caught 12 fish

Congratulations Ted!!!

Example 3
Alexis went shopping and bought a number of different
items. We need to enter the amount of money in her
purse and the price of each item to calculate the total
amount. After all the prices are entered, a price of 0
(zero) is entered as a sentinel to indicate that she has
finished selecting items to buy. If the total amount she
spent is more than R100 she’ll receive a discount of
3.5%. If the money in her purse is enough to pay for her
shopping, we need to calculate and display how much
money she will have left in her purse after she’s
received her change, if any. If she doesn’t have enough
money to pay for all the items, a message is displayed
indicating how much more money she needs to pay for
her shopping.

Planning
Table 3: Input and output variables for Example 3
Description Type Variable name

Input Price of item Real price

Money in purse Real purseMoney

Intermediate Total amount Real total

Output Money left in purse Real change

Money still needed Real shortMoney

Table 4: IPO chart for Example 3


Input Processing Output

price Prompt for input values change

purseMoney Enter price and purseMoney shortMoney

Calculate total

Test purseMoney

Calculate change or shortMoney

Display results
Algorithm

These two sets of data could be used as test data:


Data set 1

The amount in her purse is R709.55

Item 1 R150.50

Item 2 R285.70

Item 3 R397.42

Desk checking:

The total amount she spent is R833.62

This amount is more than R100, so she receives 3.5%


discount

The amount now due is R833.62 – R29.18 = R804.44

She needs R804.44 – R709.55 = R94.89

Data set 2

The amount in her purse is R75.00

Item 1 R3.00

Item 2 R25.50

Item 3 R21.60
Item 4 R7.80

Desk checking:

The total amount she spent is R57.90

This amount is not more than R100, so she doesn’t get


a discount

The amount in her purse is now R75.00 – R57.90 =


R17.10

Output:
Alexis needs R94.89 more to pay for her
purchases

Alexis has enough money, she now has R17.10


in her purse

1.5 Examples of Do-until


loops
We discussed do-until loops when we covered post-test
loops in section 1.2, explaining that they are used to
test a condition at the end of the loop.
Example 4
Angel has offered to pick strawberries for her mother,
who wants to make jam. She needs between 4.5 and
5.5 kilograms of strawberries for the jam. Angel, who is
only a little girl, can pick and carry between 400 and
900 grams of strawberries at a time, which she puts
into her mother’s container on the scale. The user is
asked to enter the weight of the strawberries in grams
each time Angel brings strawberries. The program must
calculate and display how many times she has to go to
the garden to pick strawberries before her mother has
enough for jam. The program must also display the total
weight of the strawberries picked.

Planning
Table 5: Input and output variables for Example 4
Description Type Variable name

Input Weight in grams Real weight

Output Number of times Integer noTimes

Total weight in kg Real totWeight

Table 6: IPO chart for Example 4


Input Processing Output

weight Prompt for weight noTimes


Enter weight totWeight

Count noTimes

Accumulate totWeight

Display noTimes, totWeight

Algorithm

Note that in a post-test loop, the statement to


assign an initial value to the variable that controls
the loop can be done as the first statement in
the loop because the value will only be tested at
the end of the loop. It can then serve as the
consecutive input statements as well, so no
additional statements are needed for this
purpose at the end of the body of the loop, as
was the case with the pre-test loop.

It is not necessary to test for weight less than


5.5 kg in the loop statement because as soon as
the weight is more than 4.5 kg it will not exceed
5.5 kg.

Test data
Possible input values with respective output results:

Enter the weight of the strawberries in grams


Angel picked 500

Enter the weight of the strawberries in grams


Angel picked 88O

88O is not a valid input value, please re-enter

Enter the weight of the strawberries in grams


Angel picked 880

Enter the weight of the strawberries in grams


Angel picked 720

Enter the weight of the strawberries in grams


Angel picked 450

Enter the weight of the strawberries in grams


Angel picked 570
Enter the weight of the strawberries in grams
Angel picked 770

Enter the weight of the strawberries in grams


Angel picked 360

Enter the weight of the strawberries in grams


Angel picked 320

The number of times Angel picked strawberries


is 8

She picked a total of 4.570 kg of strawberries

2. Examples of flowcharts
for pre-test and post-test
loops
The two flowcharts shown here set out the logic for
entering the marks of 10 students, then calculating and
displaying the average of their marks. The first
flowchart shows this being done with a pre-test loop
(do-while) and the second shows a post-test loop (do-
until). In both cases, the marks for all students are
entered and accumulated in the loop and the average is
calculated and displayed at the end of the loop.
Figure 1: Flowchart representing a Do-while loop
The loop in Figure 1 is clearly a pre-test loop because
the condition is tested in the beginning and the
statements in the body of the loop will be executed only
while the condition is true. If the condition is not true the
first time, the loop will not execute at all.
Figure 2: Flowchart representing a Do-until loop

The loop in Figure 2 is clearly a post-test loop because


the condition is tested at the end of the statements in
the body of the loop, so the loop will always execute at
least once. Because this loop will execute until the
condition is true, the condition will be the opposite of the
condition in the do-while example in Figure 1.

Exercises
1. Write an algorithm to calculate and display the
sum of the first n numbers of the following series:
(Enter a value for n.)
1.1. 1, 1, 2, 3, 5, 8, 13, 21, …
1.2. 1, 2, 4, 7, 11, 16, …
Determine the output of the following
algorithms.
2.1.
2.2.

2.3.

2.4.
2.5.

3. Study the following algorithms, then


predict how many times the message “this
is output” will be displayed on screen.
3.1.

3.2.

4. Do the planning and write an algorithm


for the following questions. Each problem
contains a do loop. When planning your
algorithm, decide which type of loop will be
best suited to solving the particular
problem (pre-test or post-test). If the
problem contains decisions to be made,
decide whether you’ll use an if statement
or a select case statement. You can
assume that all the input data for the
following questions will be valid.
4.1. A programmer is asked to do an
invoice of a telephone account for a
subscriber. The input to this program is the
telephone number dialed and the length of
the call in minutes (integer). The fees are
50 cents for the first minute and 30 cents
for every minute thereafter. The telephone
number and cost of the call must be
displayed for every call. The total amount
due by the subscriber must be shown at
the end of the invoice. A telephone number
of 9999 serves as a sentinel.
4.2. The salesmen working at the Tall Man
Company earn a basic salary of R1 850
per month. They also earn commission on
their sales. On a sales amount of less than
R8 500 they receive 5.5% commission, but
if they sell more, the commission is 9%.
Each employee pays 1.5% of his
commission to his manager. Calculate and
display the net income for every
salesperson. The input is the name of the
sales person and the sales amount. The
algorithm terminates when no sales person
name is entered.
4.3. Angela went to buy groceries but left
her purse at home. Luckily she found R120
in her coat pocket and decided to buy only
the necessary items. She picked a number
of items and presented them at the till in
order of necessity. The lady at the till
scanned the barcode containing the price,
which was added to the amount due.
Determine and display how many items
Angela could buy.
4.4. The All Stars Company decided to
increase the salaries of all their
employees. Enter the employee number,
department code and current annual
salary. The increase in salary depends on
the employee’s department code, as can
be seen in the following table:
Department code Percentage increase

AY 6%

HT 6.3%

KL 6.9%

Other departments 5.8%

Display the employee number and new


annual salary of each employee. At the
end of the program, display the total
amount for annual increases as well as the
average increase amount per employee.
4.5. A ball is dropped from a specific
height to be provided in metres. This is a
real number with two decimal places, such
as 7.85. The ball bounces off the ground
to a height of half the original height. This
process repeats itself. Calculate how
many times it will bounce before the height
is less than 5 centimetres. Display this
answer on the screen.
4.6. Pule decided to save money to buy a
house. Enter this amount as well as the
amount he will be able to save each
month. He earns 0.7% interest per month
while the amount is less than R80,000 and
0.9% interest per month if the amount is
equal to or more than R80,000. The
interest is added to the total amount.
Calculate how many months he will have to
save before he has reached his goal.
Display the final amount and the number of
months.
4.7. A number of people joined the
Streamline Club during the first week of
January and the weight of each member
was written on their membership card.
During the last week of March everybody
was weighed again and their new weights
were written on their cards. Enter the
name, initial weight and current weight for
an unknown number of people. Calculate
the weight loss or weight gain and display
the results, which are the name and weight
loss or weight gain with a suitable
message. The program must terminate
when no name is entered. The average
weight loss or weight gain must then
display with a suitable message.
4.8. Jerry is not sure how much money he
has, but he knows he has between R100
and R135 in R1, R2 and R5 coins. The
user enters the price of the item Jerry
wants to buy, which doesn’t exceed R100.
Jerry pays for the item he buys by handing
one coin at a time to the salesperson. The
value of the coin is entered and is
subtracted from the amount still due.
Determine how many coins Jerry uses to
pay for an item and display this number.
Remember that you don’t know how many
coins he has or their denominations. There
may be an equal number of all the coins,
no R1 coins or no R5 coins, and so on.
Also calculate and display the amount of
change, if any.
4.9. The Walk-In restaurant is very popular
among employees in the area because
they provide home-cooked meals
consisting of meat and vegetables already
dished up. They provide different meals for
men (code = M) and women (code = L).
Children (code = C) pay half the price of a
lady’s meal. The prices are as follows:
Type of meal Price per meal

Men R65.50

Ladies R56.80

The user enters the number of different


meals available in the beginning of the
program; that is, for men, women and
children. Every time someone orders one
or more meals, the type of meal and the
number is entered. If the meals are
available, this number is subtracted from
the relevant total and then the amount due
is calculated and displayed. If there are no
meals of that specific type available, a
suitable message is displayed. If fewer
meals than the customer orders are
available, a new transaction is started.
When there are no meals left of any type,
the algorithm terminates. You can assume
that all the meals will be bought.
If you want to change the algorithm so that
not all the meals are sold, you can use
another condition to terminate the
algorithm. In this case, you can also
display how many meals, and of what
type, are not sold.
4.10. A florist wants to send coupons to
her 420 regular customers, based on the
number of orders each customer placed
during the past year, as follows:
Number of Amount on coupon
orders

2–6 The number of orders times R10

7 – 15 The number of orders times


R11.50

16 – 30 The number of orders times R14

31 or more The number of orders times R17

The user is asked to enter the name of the


customer and the number of orders
placed. Determine the value of the
customer’s coupon and then display a
message on the screen, similar to the
following:
Thank you Carol!
You receive a coupon worth R50 to collect
lovely flowers!
4.11. The learners at the Clever School
pay school fees according to their grade.
The name and the grade of the learner
must be entered. The learners in Grade 1
pay R14 for the months February to
November (excluding July). The fee
increases by R4.50 for every subsequent
grade – R18.50 for Grade 2, R23.00 for
Grade 3, and so on. Calculate and display
the name and annual school fee for each
learner at the Clever School. At the end,
the average annual school fee must be
displayed. ABCD is entered as a name
once the details of all the school’s learners
have been entered.
4.12. The manager of the Nutcracker Hotel
needs a program to print invoices for the
guests who stay at his hotel. The input to
this program is the name of the guest, the
number of nights he or she spent in the
hotel and the number of breakfasts they
had. The number of nights and the number
of breakfasts need not be the same. A
guest receives one free night and one free
breakfast for every night spent in the hotel.
You can assume that the number of free
breakfasts will never exceed the number of
the input breakfasts. The price of a night is
R340 and a breakfast costs R65. The
invoice must contain the name of the
guest, the number of nights stayed, the
number of breakfasts, the number of free
nights and the final amount due. At the end
of the program, the total amount paid by
all the guests must be displayed. Choose
your own sentinel.
4.13. People who want to hire a machine
to wash their carpets usually go to the
WishyWashy Company where they can
hire any one of three types of machines –
type A, B or C for heavy duty, ordinary and
light washes respectively. The prices are
as follows:
Type of Initial Additional cost per hour
machine cost or part thereof

A R50.00 R30.00

B R62.50 R36.25

C R74.87 R40.50

The input is the name of the client, the


code to indicate the type of machine, and
the time the machine was used (in
minutes). The amount must be calculated
by adding the initial cost to the calculated
cost for the time used. VAT of 14% must
be added to the amount to present the
final amount due by the client. At the end
of the program, a total amount, total VAT
amount and the final total amount due to
WishyWashy must be displayed. Choose
your own sentinel.
Chapter 8 Arrays

Introduction
Quite often, a programmer has to use
a number of related variables that are
of the same data type and are all used
for a specific purpose in a program, for
example the names of the 12 months.
These variables can be grouped
together in an array using a single
name, to improve the code and make it
shorter and more efficient.

Outcomes
When you have studied this chapter, you should be able
to:
understand what an array is,
initialise a one-dimensional array,
store data in a one-dimensional array,
manipulate a one-dimensional array, for
instance
• display elements in the array,

• find the highest and lowest entries in an


array,

• search an array to find a specific


element,

• access an element in the array,

• compute the total and average of all the


elements in an array,

understand and use parallel arrays,


understand and manipulate two-dimensional
arrays,
sort an array using the bubble sort method,
and
sort an array using the selection sort method.

1 Properties of arrays
An array consists of a number of related variables, and
has the following properties:

It has a single name.


A single variable in an array is called an element.
All the elements in an array are the same data type.
The position of an element in an array is called an
index or a subscript.
A one-dimensional array can be seen as one column
with many rows – one for each element in the array.

Array name
The name of an array must be descriptive. Examples:

month Array – contains the names of the 12 months


in a year
price – contains the prices of 100 items in a shop
quantityInStock – contains the quantities in stock of
120 items

Element
One element in an array is a single variable that
contains a value at a given time. Examples:

one name of a month in monthArray, such as


September
25.57, which is the price of an item in the array
called price
25, which represents the quantity in stock of a
specific item in an array called quantityInStock
An element in an array need not have an initial value.

Data type
All the elements in an array must be of the same data
type, such as String or Integer. Examples:

monthArray will be of data type String


price may be of data type Real
quantityInStock will be of data type Integer

Index
The index indicates the position of an element in the
array. The index is sometimes referred to as a
subscript. The value of an index must always be a
positive integer or zero.

The index of the first element of an array is always 0


(zero) and the index of the last element of the array is
(number of elements – 1). For example, the indexes of
an array called mathScores, which contains 30
elements, would start at 0 so the last index would be
29.
The monthArray array can be visualised as a column
with 12 row elements.

Table 1: monthArray as a column


monthArray (0) January

monthArray (1) February

monthArray (2) March

monthArray (3) April

monthArray (4) May

monthArray (5) June

monthArray (6) July

monthArray (7) August

monthArray (8) September

monthArray (9) October

monthArray (10) November

monthArray (11) December

Referencing
To refer to a specific element in an array, the name of
the array as well the index of the element is used. For
instance, monthArray(0) refers to the string value
“January” and monthArray (11) refers to the string value
“December”.

Question
Let’s see if you understand the previous concepts by
applying them to a similar example.

The names of the days in a week can be stored in an


array. Each element is called day and an index is used
to retrieve the individual values from the array.

Fill in the missing indexes and references in these


tables.

Element reference Value

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday
Sunday

How do you retrieve the third element in the array?

Would it be valid to use day(7) in your code?

Would it be valid to use day(no) in your code if the


variable no has a value of 0?

1.1 Advantages of using a


one-dimensional array
A one-dimensional array is the simplest form of an
array, consisting of one column of elements as
illustrated in the examples in the previous section. We
will now start off by explaining why arrays provide a
way to improve code to make it shorter and more
efficient.

Let’s assume that a student has written 10 tests in one


subject. The final mark must be calculated as the
average of these 10 test marks. If we only had simple
variables – also called scalar variables – we would have
to have 10 individual variables to store the 10 test
marks. Values for these 10 variables would have to be
entered 10 times when using them to calculate the final
mark for the student.
This is what the algorithm would look like:

From this, it’s clear that this method is not effective at


all. The code would be even worse if the student wrote
15 or 20 tests. However, with our knowledge of loops,
we could streamline the code.
It is surely more efficient to enter the next test mark
during each execution of the loop, and to accumulate
the total for all the tests inside the loop. However, this
doesn’t make the individual marks available at a later
stage for other references because each time a new
mark is entered, the previous value of the variable (the
previous mark) is replaced by the new mark.

Because the marks are all of the same data type and
are related to one another – all the marks are for the
same student and all of them will contribute to the
calculation of the final mark – they can also be stored in
an array.

The code to store data in an array is similar to the


previous code. However, instead of entering data into
one variable, it is entered into an element in the array.
In this example, the index of the first element is 0 and
the index of the last element is 9 because there are 10
tests to be entered. The array contains 10 elements,
each of which represents a different test mark.
After the data has been stored in the elements of an
array, it can be manipulated in the same way as normal
scalar variables. When doing calculations, you can use
all the elements in the array structure or specify
individual elements. You can also change or display the
content of an array element.

You can find the element with the highest or lowest


value in the array, sort the elements in a specific order,
calculate the average of all the elements, and much
more.

The examples that follow demonstrate how elements in


an array can be manipulated.

Example 1

Problem
Continuing with the CalculateFinalMark problem, the 10
test marks for the student must be stored in an array,
then the average of the 10 test marks must be
calculated to determine the student’s final mark. After
the final mark has been calculated, all the marks as well
as the final mark must be displayed.

Planning
Table 2: Input and output variables for Example 1
Description Type Variable/array
name

Input 10 test marks entered in Integer testMark


an array

Intermediate Total of these marks Integer totalMark

Output 10 test marks entered in Integer testMark


an array

Final mark Real finalMark

Algorithm
After the algorithm has been executed, the
variables can be represented as follows:

Table 3: Tabular representation of Example 1


array

Example 2

Problem
In this example, Example 1 will be rewritten to calculate
the final mark as the average of the nine best marks. In
this case, the lowest mark must be determined and
subtracted from the total before the average is
calculated.
Algorithm

All 10 marks will still be stored in the array and


will be available for later reference. The total of
all the marks is once again accumulated inside
the loop. However, the lowest test mark is
determined in a second loop. After this loop has
been executed, the result (the lowest test mark)
is deducted from the total to exclude this mark.
The total is then divided by nine to determine the
average or final mark. The lowest test mark
could also have been determined in the first
loop.
Output:
Test 1 = 60%

Test 2 = 65%

Test 3 = 77%

Test 4 = 45%

Test 5 = 87%

Test 6 = 93%

Test 7 = 74%

Test 8 = 39%

Test 9 = 45%

Test 10 = 70%

The final mark for the student = 68.4%

Example 3

Problem
The identity numbers of the eight employees in a
particular company are stored in an array. The manager
wants to know if a specific woman is a company
employee by entering her identity number.
Algorithm

Example 4
An array called evenNumbers, which has 44 elements
with consecutive even numbers starting at 14, needs to
be filled.

Algorithm
We can then modify the example to start at any
even number.

Algorithm

Example 5
Problem
An array called noInStock already contains the following
valid positive integer values in the 20 elements

4, 15, 38, 53, 8, 95, 129, 653, 45, 658, 12, 40, 0, 98,
74, 32, 9, 39, 25, 87

The index and value of the highest number in noInStock


need to be found and displayed.

Algorithm

Output:
The highest value in the noInStock array is: 658

It was found at index position 9


Note that the index of the first value used in the
loop structure is not that of the first element,
because the value of the first element has
already been assigned to the variable called
highest.

Exercises
1. Write an algorithm for the following:
An array called numbers contains 35 valid integer
numbers. Determine and display how many of
these values are greater than the average value
of all the values of the elements.
Hint: Calculate the average before counting the
number of values higher than the average.
2. An array called abcArray has 12 integer
elements. Populate the array using the values of
the series 1 000; 989; 967; 934; 890; ... Display
the values of all the elements.
3. An array that has 20 elements contains character
values. Use a Select Case statement to count
and display how many of these elements contain
vowels.
4. You’re given two arrays. The first has 100
elements containing integer values. The second
has 20 elements. Write an algorithm to calculate
the sum of the values of the first five elements of
the first array and store the answer in the first
element of the second array. Store the sum of
the next five elements of the first array in the
second element of the second array, and so on.
For example:

5. The array called codeArray has 45 elements and


contains codes, each consisting of three
alphabetical values. The value of the seventh
element is no longer valid so all the values of the
subsequent elements must be moved by one
position to the lower index. For example,
codeArray(12) must be moved to codeArray(11).
The code value KBD must be stored in the last
element.
6. The array called number is given the following
values:
Process the code given below and display the
new values for the array in the space provided:

7. An array called letterArray has 30 elements that


contain a sentence with one letter per element.
For example, TODAY IS A LOVELY SUNNY
DAY.
The following algorithm attempts to count how
many elements contain either an A or an E and
displays the count. It must also express the count
as a percentage of the total letter count. Identify
and correct all the errors in this algorithm.

8. Determine the value of the array called abc after


the following statements have been processed:
9. Given an array called array_s:
Determine the value of t after these statements
have been processed:

10. The array called array_m has 600 elements. The


value of the element that has the same index as
the value of the variable called ct must be
decreased by 35%, then 14% VAT must be
added to it. Write the statement to achieve this.
11. Study the following array called XYZ.
11.1. What will the value of answer be after the
following statements have been executed?

11.2. What is the value of element 4?


12. The array called number contains the following
values:
number

4
5

Process the code given below and show the new


values in the array:

13. The array called priceVal can contain 10 integer


value elements. Process the code given below
and show the new values in the array.
14. The array XYZ can contain 10 numeric elements.
Process the code given below and show the new
values in the array.
15. An array called ABC consists of 10 elements. It
currently has no values but may contain integer
values. Indicate (in the space provided) what the
values in the array called ABC will be after
execution of the following statements:
16. An array called NUM contains 50 unique integers.
In pseudocode, write only the statements
required to enter values into this array. For each
number entered, ensure that it is numeric and
that it does not yet appear in the array. If a value
already exists, display an appropriate error
message and re-enter the value.
17. Write an algorithm for the following:
17.1. Solomon sells 40 different products in his
fast food store, which he’s numbered from 1 to
40. He has decided to use a program to handle
his sales. But first a short program must be
developed to load the prices into the array in the
program.
17.2. Add statements to the algorithm to
calculate the amount due by a client. The client
orders items according to product number, giving
the required quantity. For every product, the
product number, quantity ordered, unit price and
amount for these products must be displayed.
The amount due by the client is displayed once
the product code = 99 is entered.

2 Parallel (paired) arrays


When two or more arrays are related to one another
and have the same number of elements, they are
known as parallel arrays. The elements in these arrays
need not be of the same data type.

Consider two arrays – one called code and the other


called description. The array called code contains the
following item codes by which they are identified (ab3,
kh8, vs1, gp5 and wd4), whereas the array called
description contains the following descriptions to match
the corresponding elements (chair, table, bed, cupboard
and sofa). In other words, the indexes of the two arrays
will be equivalent for a specific item.

The two arrays can also be represented as follows:


Table 4: Content of the code and description arrays
index code index description

0 ab3 0 chair

1 kh8 1 table

2 vs1 2 bed

3 gp5 3 cupboard

4 wd4 4 sofa

If we know what the value of a code element is, we


need to find the index of this value and then go to the
description array to find the description of the item in
the element with the same index.

Example 6

Problem
We need to write an algorithm to enter a code, find the
corresponding description and then display the
description on screen. If the description is not found
because code doesn’t contain the entered code, a
suitable message must be displayed.

Algorithm
Exercises
Do the planning and write algorithms to solve each of
these problems:

1. Three parallel arrays each contain 250 elements.


One contains the employee numbers, another the
department codes and the third contains the
annual salaries. Display the employee number
and department code of every employee who
earns more than R100 000 per annum.
2. Three parallel arrays related to information about
300 different items in a shop contain the item
number, the number of items in stock and the
price of the item. A real value that must be used
to increase the price of every item must be
entered. The item number and the increase in
value of the stock must be displayed for every
item.
Hint: Increase in value = new value – previous
value while value = price * number in stock.
3. Assume three parallel arrays contain the
following values.

Table 5: Three related arrays


Snack code Description Price in R

75 Chocolate 5.75

23 Soda 6.25

89 Pizza slice 8.50

41 Burger 15.85

17 Muffin 5.75

The user is asked to enter the code of the snack


he or she wants to buy, as well as the number
bought. The program must find the description
and the price in the arrays, calculate the amount,
add 14% VAT and then display the number
bought, description and total amount due on the
screen.
4. Six children took part in a series of three quizzes
each. Enter values into four parallel arrays. The
first array contains the name of each child and
the other three parallel arrays contain the points
that each child scored in each quiz. Calculate the
average number of points obtained by every child
and store these values in a fifth array. Determine
and display the name of the child who obtained
the highest points on average.
5. Two parallel arrays (stNum and stMark) contain
the student numbers and test marks for 100
students. In pseudocode, write only the
statement(s) required to display the student
numbers and the test marks for all students who
obtained a distinction in the test (75% or more).
6. Three parallel arrays contain information about
eight girls. The first array contains the first
names of the girls, the second array contains
their surnames and the third array contains their
birthdays in the format DDMM. Plan and write an
algorithm to display the first name, surname and
birthday in the following format:
Jenny Nkosi, 17 May
You can assume that all three arrays already
contain valid values.

3 Two-dimensional arrays
A one-dimensional array consists of a column that
contains a number of row elements, whereas a two-
dimensional array consists of a number of rows and a
number of columns. The difference between a one-
dimensional array and a two-dimensional array can be
explained by means of the following example: The
minimum temperature for the past seven days of the
week, as can be seen in the following table:

Table 6: A one-dimensional array


3

This one-dimensional array can be expanded to a two-


dimensional array when the maximum temperatures are
added, as follows:

Table 7: A two-dimensional array


3 18

4 22

5 23

3 21
2 24

3 19

6 25

The particulars of a single day can be found in a row –


for instance, row 0 contains the minimum and maximum
temperatures for day 1, that is 3 and 18. Similarly, row
3 column 0 contains the minimum temperature for day 4
and row 3 column 1 the maximum temperature for day
4.

We can now name the array temperatures, which


consists of seven rows and two columns. When
referencing a particular element, we need to specify
both the row and the column number:

temperatures (2, 1) = 23

temperatures (4, 0) = 2

Example 7
There are 20 students in a class at the college. Their
names and student numbers are stored in two parallel
arrays in order of student number.

Every student wrote four tests. The test scores are


stored in a two-dimensional array. We need to calculate
the final mark for every student – the average of the
four test marks – and store it in a third parallel array.
We’ll use the three parallel arrays to display all student
numbers, followed by the student name and the final
mark. Then we’ll determine the student who obtained
the best final mark and display the best final mark and
student name.

For the purpose of this example you can assume that all
the data is already stored in the arrays.

Planning
The following arrays will be used:

Table 8: Planned arrays for Example 7


Student stNum one 20 rows
numbers dimensional

Student names stNames one 20 rows


dimensional

Student marks stMarks two 20 rows, 4


dimensional columns

Final marks stFinalMark one 20 rows


dimensional

Other variables used:


The best mark best

A student’s total marks total

Variable for student loop st

Variable for test loop test

Algorithm
Exercises
Do the planning and write algorithms to solve each of
the following problems:

1. The array called wArray has 20 rows and 24


columns and every element contains a valid
integer. Display every row number and the
number of elements in the row that has a value
greater than 50.
2. The manager of the Super Store decided to
increase the limit on the accounts of all his good
customers. He stores customer data in two
parallel arrays; one for the account numbers and
one for the account limit in Rand. He also has a
two-dimensional array with 12-column rows that
correspond to each row in the parallel arrays.
Every row in the two- dimensional array, which
represents the 12 months of the year, contains
the amounts that the customer spent in the shop,
but has not yet paid. The program must increase
the account limits for every customer who owes
less than 75% of the current limit by 12%.
3. The Best Buys supermarket uses a one-
dimensional array to store department codes
consisting of three characters each, and a two-
dimensional array to store the sales for the past
month per department. The two-dimensional
array stores information for seven departments
and every department can store 1 000 sales
transactions. The seven department codes must
be entered in the beginning of the program and
all the sales amounts must be initialised. The
sales transactions are entered into the two-
dimensional array by entering the department
code and the sales amount.
Use the department code to find the index of the
department and insert the amount into the next
available element. At the end of the program the
department code and the total sales amount
must be displayed. Write code to eliminate all
possible errors including more than 1 000 sales
per department.
4. Two parallel arrays store the following
information for seven employees. The first array
is a one-dimensional array that contains the
seven employee numbers. The second array is a
two-dimensional array that contains the basic
monthly salary in the first column, the bonus in
the second column and the net salary in the third
column. Therefore, every row in the two-
dimensional array will contain the basic monthly
salary, bonus and net salary for the employee
whose number is stored in the parallel array in
the same position.

Table 9: Parallel arrays to use with Question


4
Emp B Month Bonus Net
no Sal salary

Emp 1234 5000.00


1

Emp 2345 6000.00


2

Emp 3456 6500.00


3

Emp 4567 7000.00


4

Emp 5678 8650.00


5

Emp 6789 9800.00


6

Emp 7890 9950.00


7

The employee numbers are available in the first


array. The basic monthly salaries are available in
the second array. Do the planning and write an
algorithm to complete the rest of the array, using
the following:
Bonus = 75% of the basic monthly salary
Deductions from basic monthly salary:
Tax = 18%
Medical aid = R425
Display all the values on screen.
5. Execute the following algorithm and store the
answers in an array called arrayC, which has
nine rows and ten columns. Draw the array on
paper.

4 Sorting arrays
It is advisable to sort the values of the elements in an
array into a specific sequence – ascending or
descending order – according to a specific field(s).

Suppose a programmer has to find a specific value in


an array that has numeric elements. If the programmer
searches for the number in an unsorted array, it’s
possible that all the elements will have to be searched
before the number is found or not found. But if the
values of the elements are sorted in ascending numeric
sequence, the programmer only searches until the
number is found or until the next number in the array
has a higher value than the number the programmer is
searching for.

Table 10: An unsorted array


20

15

36

Table 11: The array sorted in descending order


36

20

15

Example: The programmer needs to find if the number


16 is present in the array.
When searching the unsorted array, all the elements are
compared to 16 before it is clear that 16 is not present.
But when searching the sorted array, there will only be
3 comparisons, to the values 36, 20 and 15 where the
last value is less than 16 when it is evident that 16 is not
in the array.

When using character or string values, the order is:

Ascending: A to Z

Descending: Z to A

Remember that the names in a telephone directory are


sorted in ascending sequence.

4.1 The bubble sort method


There are many sorting techniques. One of the simplest
to understand is a technique called the bubble sort.
Elements in the array are compared to each other in
pairs, and when an element is not in sequence, it trades
places with the other element.

We’ll illustrate this concept using an example to sort in


ascending order, as shown in the following array.

25 Comparing the first two elements: 25 is less than 47. Nothing


changes.

47

16

17

25 Comparing the next two elements: 47 is greater than 16. Values


are swapped.

47

16

17

25 Comparing the next two elements: 47 is greater than 2. Values are


swapped.

16

47

17

25 Comparing the next two elements: 47 is greater than 17. Values


are swapped.

16

47

17

25 At this stage, you will notice that the highest value (47) is in the
last position.

16

17

47

Now we’re going to deal with the first four positions.

16 Compare the first two elements: 25 is greater than 16. Values are
swapped.

25

17

47
16 Comparing the next two elements: 25 is greater than 2. Values are
swapped.

25

17

47

16 Comparing the next two elements: 25 is greater than 17. Values


are swapped.

17

25

47

At this stage, you will notice that the second highest


value (25) is in the second last position.

We would continue comparing the values the first three


positions in the same manner, then the first two
positions, after which the values in the array would be in
ascending order.

Example 8
Problem
An array called petNames has 15 elements, each of
which contains the name of a pet. The values of the
elements must be sorted in ascending sequence. In this
example the bubble sort method is used to achieve the
sequence.

Algorithm

4.2 The selection sort


method
The selection sort method selects the smallest value
from the entire array and exchanges it with the first
element in the array. Following this exchange, the
second smallest element is selected from the array and
exchanged with the second element. This process is
continued until the entire array is in ascending order.

Table 12: An ascending selection sort

The arrows in the table indicate the movements of the


smaller numbers. Note that they’re exchanged with
bigger numbers.

To sort an array into descending sequence, the entire


process is just reversed to start with the biggest value,
which is exchanged with the first element in the array,
and so on.

Example 9
Now let’s sort the petNames array we used in Example
8 in descending order.
Note that (n – 1) exchanges will take place if there are
n elements in the array. In this example the selection
sort method is used to achieve the sequence.

Algorithm

Exercises
1. Twenty athletes took part in a race and their
times in minutes were stored in an array as real
numbers. Use a bubble sort to sort the times (in
ascending or descending order, depending on
your logic) and then display the times of the
fastest three athletes (lowest times).
2. Repeat Question 1 to include a parallel array that
contains the names of the athletes. When doing
the bubble sort, remember to swap the names in
the names array at the same time that you swap
the times in the times array.
3. An array called numberArray contains an odd
number of integer values. Use a selection sort to
sort the array in ascending order, then display
the smallest (first) value, the middle value and the
largest (last) integer. Enter the number of
elements in the array in the beginning of the
program, as well as the values of the elements.
Chapter 9 Function
procedures and
subprocedures

Introduction
Using function procedures and
subprocedures enables you to split
large, complex algorithms into smaller
modules , which makes the computer
coding more effective. Lines of code
that perform a specific task that is
repeated often would typically be
coded as a separate procedure. Such
a procedure is written just once and
reused whenever the task needs to be
performed.

Large and complex applications can


also be broken down into smaller,
more manageable tasks. It often
happens that two or more
programmers work on the same
application at the same time, each on
a different subprocedure. Because the
modules are now shorter, it should be
more understandable to other
programmers who might read and
need to use it.

Both a subprocedure and a function


procedure perform a task. However, a
function procedure – also called a
function – always returns one value
that has been determined or
calculated within the function.

Outcomes
When you have studied this chapter you should know
and understand the following:
modules and modularisation,
drawing a hierarchy chart,
the purpose and use of value parameters and
reference parameters,
the use of function procedures,
writing a statement to call a function, and
writing the corresponding function header,
statements in the loop and a statement to
return an answer,
writing functions with and without parameters,
the use of subprocedures,
writing a statement to call a subprocedure,
and writing the corresponding subprocedure
header and statements in the subprocedure,
and
writing subprocedures with or without
parameters.

1 Modules and
modularisation
Modularisation divides the solution to a problem into
smaller pieces – called modules – to improve the
flexibility of a program and shorten its development
time. A module is therefore part of a program. Large
and complex programs can be divided into
independently developed modules. Each module is
made up of one or more statements to perform a
specific task. The various modules are then linked to
form a working program.

Modules can take several forms, depending on the


programming language used. Two such forms are
function procedures and subprocedures, which we′ll be
discussing in this chapter.

2 Hierarchy charts
A hierarchy chart is a diagram that provides a global
view of the modules in your program and how they link
together to function as a complete program. A hierarchy
chart doesn′t contain any detail, just the name of each
module and an indication of how the modules are
related.

When drawing a hierarchy chart, you always start by


placing the main module at the top. Through connecting
lines, you can then see which modules will be called
from the main module. These modules, in turn, can call
other sub modules.

Once a programmer has identified all the steps required


to solve a problem, he or she can group steps that have
a common goal into logical groups to see which of the
steps can be coded in a separate module, to break the
problem into smaller chunks and simplify the process.

For example, to calculate students′ final marks, the


programmer may decide to use one module to obtain
the input values and two more modules to calculate the
year mark and the final marks. The displaying of the
final marks could also be done in a separate module.
Figure 1 shows a sample hierarchy chart based on this
program.

Figure 1: A hierarchy chart

Note that each module has a descriptive name.

3 Parameters
Before we can study function procedures and
subprocedures, we need to understand what
parameters are. A parameter is data (variables or
values) that is sent to a function or a subprocedure,
which it needs to perform the task it has to do. A
parameter may also contain the address of an answer
when dealing with a subprocedure.
There are two types of parameters:

value parameters and


reference parameters.

3.1 Value parameters


Value parameters can be explained using examples
from everyday life.

Joseph has a page on which he wrote some numbers.


He makes a copy of the page and sends it to Solly. In
programming terms, Joseph has sent value parameters
to Solly, who could be a function or subprocedure that
needs the parameters.

Solly may do anything he wishes with the parameters


because Joseph still has the original and doesn′t need
the copy anymore. So if Solly changes a value
parameter, it is changed only on his copy and not on the
original.

Solly may use these parameters to calculate a total. He


may keep this total for his own use or he could return it
to Joseph. If he keeps it, the total could be displayed or
it can be used in other calculations. If he returns the
value of the total to Joseph, Solly is a function and not a
subprocedure because a function always returns an
answer.

Joseph will now have his original copy as well as a total


that doesn′t exist on his original copy.

Another everyday example is that Sam may tell Henry


how much money he has in his bank account. In
programming terms, he′s sending a copy or value
parameter to a function called Henry. Function Henry
will now be able to calculate how much money the two
of them have in total, but he cannot change the amount
in Sam′s account.

In the generic planning of programs (algorithms), we will


use the prefix val to identify a value parameter.

3.2 Reference parameters


Again, we can use everyday examples to explain
reference parameters.

Josephine receives a post box number and the key to


the post box at the post office. She goes to the post
office and opens the box to find a letter in the box. She
can now put something else in the box that the owner
will collect. She can also receive more than one post
box number (address) and the corresponding keys to
return different letters to the owners.

In programming terms: Two owners of post boxes give


their keys and post box numbers – two reference
parameters – to subprocedure Josephine. This means
that the addresses of the post boxes are known to
Josephine and she has access to the post boxes. In
computer terms, these post boxes represent different
areas in memory of the computer. Subprocedure
Josephine may now remove the letter, put another letter
in the post box or just write something else on the letter.
But bear in mind that, while the instructions in the
subprocedure apply, changes are issued within
subprocedure Josephine. These changes take place
inside the post boxes.

Returning to the banking example in Section 3.1, if Sam


gives subprocedure Henry access to his banking
account by giving him the number and pin code,
procedure Henry could withdraw or deposit an amount
of money in Sam′s account. These changes would take
place in Sam′s account according to instructions given
by subprocedure Henry.

In the generic planning of programs (algorithms), we will


use the prefix ref to identify a reference parameter.
4 Function procedures
A function procedure, which we′ll refer to as a
function, consists of a number of statements used to
execute a single task. A function always returns a value
and can receive value parameters. However, it′s
possible that it may not receive parameters.

4.1 The function call


Calling statements in other parts of the algorithm
activate or call a function. When the function has been
processed, control returns to the calling statement. The
list of parameters in a function is known as an
argument list .

There are various types of calling statements, such as


assignment statements, if statements and display
statements, as can be seen in the following examples.
In each case, the actual call consists of the name of the
function followed by an argument list in brackets. An
argument list can, however, be empty.

An assignment statement
Send two values, number1 and number2, to a function
named CalcSum, which will calculate the sum of the two
numbers.

Call the function:

sum = CalcSum(number1, number2)

The answer will be stored in sum.

CalcSum is the name of the function whereas number1


and number2 are the arguments (two value
parameters).

A display statement
Use the same example, but don′t store the answer in
sum; instead display the sum of the two numbers.

display “The value of the sum is: ”, CalcSum(number1, number2)

The function CalcSum is called while sending the two


value parameters (number1 and number2) to the
function. The sum is returned to the calling statement
and displayed on the screen.

An if statement
if CalcSum(number1, number2) > 40 then
display “The sum is greater than 40”

endif

The function CalcSum is called while passing the two


value parameters to the function to calculate the sum of
the two numbers. The sum is returned to the calling
statement and then used in the if statement.

4.2 The function


The first line of a function – called the function header
– contains the word function, a function name and a
list of parameters. Again, the parameter list can be
empty.

Format: Function NameOfFunction(parameter list)

The last statement of the function to be processed will


be a return statement (exit the function) that sends the
result of the function to the calling statement. If a
function contains an if statement, it may contain more
than one return statement in different parts of the if
statement. However, it will execute only one of these
statements and return only one value depending on the
outcome of the if statement. The data type of the value
returned must be the same in all the return statements.

Format: return value

The name of the function is associated with the data


type of the value that is returned to the calling module.
This is why a function may return only one value.

Example:
Write the calling statement to call a function that
calculates the sum of two numbers as well as the
function to store the answer in the variable sum.

Calling statement:

sum = CalcSum(number1, number2)

The function to calculate the sum of two numbers will


be:

Function CalcSum(valNumber1, valNumber2)


total = valNumber1 + valNumber2

return total

Important notes
The function name used in the calling statement and
the function name in the function header must
always be the same.
The names of the arguments and parameters need
not be the same.
The order of the variables in a calling statement′s
argument list and the parameters in the function
header must always be the same.
The number of variables in a calling statement′s
argument list and the number of parameters in the
function header must always be the same.
The name of the value returned by the function need
not be the same as in the calling statement.
The arguments are only the names of the applicable
variables in the calling module. On the other hand,
the parameters in the header must indicate whether
the parameter is a value parameter or a reference
parameter – in other words, whether a copy or an
address has been sent.
The function can also be written as follows, where the
variable total is replaced by the expression valNumber1
+ valNumber2.

Function CalcSum(valNumber1, valNumber2)

return valNumber1 + valNumber2

4.3 Calling a function and


using a function
The examples that follow demonstrate how to do the
planning and write algorithms that use functions and
function calls to solve the problem.

Note
In the generic planning for the program examples that
follow, we′ll use the prefixes val for a value parameter
and ref for a reference parameter. These prefixes are
used only in the function or subprocedure and not in the
calling module or calling statement.

Example 1
Reginald went to a shop to buy a number of fruit bars.
The number bought and the price of a fruit bar are
entered in a main procedure. These numbers need to
be sent to a function to calculate the amount due. The
amount due must include 14% VAT. The calculated
value must be returned to the main procedure and
displayed on the screen.

Figure 2: Example 1 hierarchy chart

Planning
Table 1: Input and output variables for Example 1
Algorithm

Important notes
This example illustrates that the function and the
main program are two completely separate entities.
The main program and the function communicate
using parameters.
If the function does not receive the number and the
price, it will not be able to calculate the correct
answer. This is because number and price are local
to the main module where they have been declared
and cannot be accessed by the function unless the
function receives them as parameters.
If the amount due is not returned to the main
procedure, the main procedure will not have the
correct value to display.
The parameters in the call statement′s argument list
(in the main procedure) are in the same order as the
parameters in the function header′s parameter list.
In most programming languages, the functions and
subprocedures are coded before the main program,
so this book will follow that convention in the
example algorithms.

Example 2
Write an algorithm to enter three test marks for a
student. A function is called to calculate the average
mark. Another function is used to indicate whether the
average mark is a pass mark (>=50) or a fail mark. The
average as well as the result must be displayed on the
screen. All input and output must be done in the main
procedure.

Figure 3: Example 2 hierarchy chart

Planning
Table 2: Input and output variables for Example 2
Algorithm
Exercises
1. Identify and correct all the errors in the following
function call and its corresponding function
header.
decPay = CalcPay(Hours, Tariff )
Function Pay(refTariff, valHours)
2. Determine the output of each of the following
algorithms:

2.1.

2.2.

3. The formula to calculate the Body Mass Index for


a person is as follows:
BMI=WeightHeight2
Write a complete algorithm to enter a person′s
weight and height and to send the variables
containing these values to a function that must
calculate and return the person′s Body Mass
Index.
The main module must then send the Body Mass
Index to a second function that must return a
message indicating the category the person
belongs to. These are the categories:

Table 3: Body Mass Index


BMI Category

0 – 15 Starvation

> 18.5 – 25 Normal

> 25 – 30 Overweight

> 30 – 40 Obese

> 40 Morbidly obese

The weight, height and Body Mass Index as well


as the status must be displayed as output in the
main module.
4. Study each of the following function calls, then
write the complete function to calculate and
return the answer.
4.1. BestMark = DetermineBest(Test1, Test2,
Test3)
The function must determine and return the best
of the three test marks.
4.2. Average = CalcAverage(Test1, Test2, Test3)
The function must calculate and return the
average of the three test marks.
4.3 Pay = CalcPay(Hours, Tariff )
The function must calculate the person′s pay by
multiplying the hours by the tariff per hour. If
there are more than 40 hours, the person
receives 1½ times the tariff for all hours over 40.
4.4. NetMonthSal = CalcSal(GrossAnnSal,
TaxPercentage)
The function must calculate and return an
employee′s net monthly salary from their annual
gross salary as well as the percentage tax that
the person must pay. Deduct the tax amount from
the monthly gross salary to calculate the monthly
net salary.
5. Write a complete algorithm with functions to
solve each of the following problems:
5.1. Enter the radius of a circle, then call one
function to calculate the circumference and
another function to calculate the area of the
circle. Display the calculated values on the
screen.
5.2. Elize buys a number of boxes of Smarties.
You are asked to enter the number of boxes and
the unit price of a box of Smarties. The amount
due is calculated as the number bought multiplied
by the price. However, a customer may receive
discount depending on the number of boxes
bought, as can be seen in the table below. All
calculations for the amount due must be
calculated in a function. The function must receive
the number bought and unit price. Display the
amount due in the main procedure.

Table 4: Discount per box


Number of boxes Discount

1–7 No discount

8 – 20 2.5%

21 and more 4.75%

5.3. You are a bookkeeper for a company and


need to divide all the amounts you paid to
suppliers into the basic amount and the VAT,
which is 14%. For example, if the amount is
R114, the basic amount will be R100 and the
VAT amount will be R14. Enter the final amount,
calculate the VAT in one function and the basic
amount in another function. Display the basic
amount and the VAT on the screen.
5 Subprocedures
A subprocedure can also be used to solve a specific
part of a problem, and has the following properties:

It can receive value parameters to use in the


subprocedure.
It can receive reference parameters.
It doesn′t return a value.
It is able to manipulate data outside the
subprocedure at specific addresses, as given in the
reference parameters. In other words, it can change
more than one value.

5.1 The subprocedure call


The syntax of the subprocedure call used in an
algorithm is:

call NameOfSubProcedure (argument list)

Study the following subprocedure call:

call Calculations(number1, number2, sum, product)


display “The sum of ”, number1, “ and ”, number2, “ = ”,
sum

display “The product of ”, number1, “ and ”, number2, “


= ”, product

Calculations is the name of the subprocedure, and


number1 and number2 are value parameters containing
numeric values. These values may not be changed by
the subprocedure because they are displayed in the
succeeding statements. sum and product are two
reference parameters. They contain addresses of
variables. The values in these specific addresses may
be changed.

Actually, we′re going to use the subprocedure to


calculate two values – the sum and the product of the
two numbers.

5.2 The subprocedure


The syntax of the subprocedure header line used in
the planning is:

Sub Name Of SubProcedure (parameter list)


Here′s the subprocedure header for the subprocedure
call in the previous paragraph:

Sub Calculations(valNo1, valNo2, refSum, refProduct)

Calculations is the name of the subprocedure, which is


the same name used in the subprocedure call.

valNo1 and valNo2 are value parameters containing the


numeric values sent from the subprocedure call. refSum
and refProduct are two reference parameters that
contain the addresses of the sum and the product.
These two parameters will contain the answers, which
will also be accessible from the main module.

Here′s the entire subprocedure:

The subprocedure uses parameters to receive “copies”


of the values of number1 and number2. refSum and
refProduct contain the addresses of the area in memory
where the subprocedure must store the result of the
calculation. The calling module will also refer to these
addresses and will therefore be able to retrieve the
answers. End Sub terminates the subprocedure.

A function or subprocedure can be called from a main


procedure or from any other function or subprocedure
as can be seen in some of the examples.

5.3 Calling an independent


subprocedure and using a
subprocedure
The examples that follow demonstrate how to do the
planning and write algorithms that use subprocedures
to solve a problem.

Example 3
Danny invested an amount at the Save-a-Lot Bank,
which must be entered at the beginning of the algorithm.
The monthly interest rate is also entered. The algorithm
must calculate and display the amount of interest
earned as well as the balance at the end of every
month for the next 15 months. At the end of the
algorithm the total amount of interest must be
displayed. This example uses functions and
subprocedures where possible. A monthly interest rate
is used to test the program, for example an annual
interest rate of 10% = 0.83% per month.

Figure 4: Example 3 hierarchy chart

Planning
Table 5: Input and output variables for Example 3
Description Type Variable name

Main procedure
(EarnInterest)

Input Amount Real amount

Interest rate Real rate

Output Amount Real amount

Monthly interest Real monInt

Total interest Real totInterest

Subprocedure
(CalcNewValues)
Parameters Copy of interest Real valRate
rate

Address of Real refAmt


amount

Address of Real refMonthInterest


interest rate

Subprocedure
(AccSum)

Parameters Copy of monthly Real valMInterest


interest

Address of total Real refTInterest


interest amount

Subprocedure
(DisplayResults)

Parameters Copy of month Integer valMonth


number

Copy of amount Real valAmt

Copy of monthly Real valMInt


interest amount

Algorithm
Example 4
This example shows the planning and an algorithm to
calculate the final marks students obtained for
Programming 3. The final mark is calculated on the
marks of various assessments and their particular
weightings:

Table 6: Assessments and weightings


Assessment Weighting

Test 1 15%

Test 2 20%

The better of two class test marks 15%

Examination 50%

We′ll code a function to determine and return the higher


mark of two class tests. A subprocedure will be used to
calculate the final mark and determine whether it is a
pass or fail (message), and another subprocedure will
display the mark and the message result.
Figure 5: Example 4 hierarchy chart

Planning
Table 7: Input and output variables for Example 4
Description Type Variable name

Main procedure
(CalcFinalMark)

Input Mark for test 1 Integer test1

Mark for test 2 Integer test2

Mark for class Integer clTest1


test 1

Mark for class Integer clTest2


test 2
Exam mark Integer exam

Intermediate Better class test Integer betterClassTest

Output None

Function
(CalcClMark)

Parameters Copy of class Integer vaClMark1


test 1 mark

Copy of class Integer vaClMark2


test 2 mark

Output Better class test Integer betterMark


mark

Subprocedure
(CalcValues)

Parameters Copy of test 1 Integer valTest1

Copy of test 2 Integer valTest2

Copy of better Integer valClassTest


class test

Copy of exam Integer valExam


mark

Intermediate Final mark Real final

Indication – String message


pass or fail

Subprocedure
(DisplayResults)

Parameters Copy of final Integer valFinalMark


marks

Copy of result String valMessage


message

Output Final mark Real valFinalMark

Message String valMessage

Algorithm
Important note
As mentioned earlier, a function or subprocedure can be
called from a main procedure or from any other function
or subprocedure. In Example 4 a function was used to
determine the better class test and a subprocedure
was used to determine the result. A second
subprocedure is called from this subprocedure to
determine and display the result. This can also clearly
be seen from the hierarchy chart.

5.4 Functions and


subprocedures without
parameters
It is possible that a function or subprocedure can be
called without sending it any parameters. For instance,
a function can be called where a value must be entered
and validated until it is correct. When a correct value is
entered, it must be returned to the calling module.

Example 5
A function is called to enter the discount that applies to
a product. The discount may never be more than 25%.
Exercises
1. What will the exact output be after each of these
program segments has been executed?
1.1.
1.2.
2. An athlete runs a long distance from one town to
another. In the main algorithm, enter the name of
the athlete, the distance between the two towns
and the actual distance that the athlete can run
per day. Call a subprocedure to calculate the
number of days the athlete will need to run the
entire distance between the two towns. Display
the answer in the main algorithm.
Rewrite your solution, but call a function instead
of a subprocedure.
3. Study each of these subprocedure calls, then
write the complete subprocedure for the required
algorithm.
3.1. Call SortTests(test1, test2, test3)
The subprocedure must place the best test
mark in the first parameter, the second-
best test mark in the second parameter
and the lowest mark in the third
parameter.
3.2. Call CalcNetSal(GrossSal, 23.5,
TaxAmt, cNetSal)
The subprocedure must receive a gross
salary and a tax percentage (23.5%, in
this case). It must then calculate the tax
amount for the employee, then the net
salary by deducting the tax amount from
the gross salary. All values will be
applicable to a month′s salary. The tax
amount and net salary must be available to
the calling module after they′ve been
calculated.

4. Write a complete algorithm to solve each of the


following problems. Use functions and
subprocedures wisely.
4.1. Ronnie sells newspapers on the
corner of Long and Main streets from
Mondays to Saturdays. At the start of the
program, enter the profit he earns per
newspaper, then go into a loop to input the
number of newspapers he sold per day in
a subprocedure. Call a function to
calculate his profit per day and accumulate
his profit for the week in a subprocedure.
Display his profit for the week in the main
module.
4.2. A fleet of taxis transports passengers
from Main Square to various parts of the
town. The owner of the taxis needs to
know how many passengers travel to
region A, region B or region C on a
specific day. He earns 50 cents profit on a
passenger travelling to region A, 65 cents
to region B and 72 cents to region C.
Enter the region for each passenger.
Region code “Z” will terminate the input.
Call two subprocedures: one to calculate
how many passengers travel to each of
the regions and another to calculate the
profit earned by the owner. Display the taxi
owner's profit for the day on the screen.
4.3. Max Contractors has five employees,
each of whom receive a weekly wage. The
basic wage is entered. An employee may
also borrow money from Max Contractors,
in which case 25% of the loan is
subtracted from the employee′s weekly
wage. If this amount is more than R50,
then R50 is subtracted. But if R50 is more
than the remainder of the loan amount, the
remainder is subtracted. The loan amount
is also entered. The program must display
the amount the employee will receive as
well as the remaining amount of the loan.
These answers must be calculated in a
subprocedure.
4.4. Do the planning and write an algorithm
to solve the following problem.
At the Cheap Unfair Store, salaries for
employees are computed as follows: A
male employee earns a basic salary of R2
500 per month. He receives an additional
R250 for every year of experience. He
also receives an additional R550 if he has
a qualification. Males pay 10% tax and 8%
to the pension fund, which are deducted
from the gross salary to produce the net
salary. Female employees earn a basic
salary of R2 000 per month and an
additional R200 for every year of
experience. Females receive an additional
R450 if they have a qualification and they
pay 9.5% tax and 7.5% to the pension
fund. Enter the gender, years of
experience and whether the person has a
qualification. Call a separate function for
females and males, each of which must
return the gross monthly salary. Then call
a procedure to calculate the tax amount
and pension fund amount. Call another
function to return the net salary for this
person. Display the gross and net salaries
in the main module. You can assume that
the input values will be valid.
4.5. The admission requirements to study
IT at the ABC University are as follows:
• Admission into the general first year
(mainstream students):

• An APS score of 18 and at least 3 for


English and 4 for Mathematics

• Admission into the IT Foundation


programme:

• An APS score of 18 and at least 3 for


English and Mathematics or

• an APS score of 20 with at least 5 for


Maths Literacy and 3 for English

• The APS score is calculated by


adding the scores for the best 6
subjects together, excluding the score
for Life Skills and any score of 2 or
less.

Table 8: Two examples of APS scores


Example 1 Example 2

English 3 English 4

Ndebele 3 Northern Sotho 3

Mathematics 4 Maths Literacy 5

Biology 4 Physical Science 2


Life Orientation 5 Art 3

Technical Drawing 4 Life Orientation 6

Business Studies 4 Accounting 4

APS 22 APS 19

The person in Example 1 will qualify to


enter directly into the main stream in the
general first year, but the person in
Example 2 won′t be considered for either
the general first year or the foundation
course.
Write an algorithm with function
procedures and subprocedures to indicate
to prospective students whether they
qualify for the IT course, the IT foundation
course, or neither.
The main procedure must ask the user to
enter the following fields:
• Reference number of prospective
student

• Initials and surname of prospective


student

• Mark for English

• Mark for Second Language


• An indication whether the prospective
student has Mathematics, Maths
Literacy or neither of these subjects. If
the student has either Maths or Maths
Literacy, their mark must be entered. If
the student doesn′t have either Maths
or Maths Literacy, a suitable message
rejecting the application must be
displayed and the program must not
continue with the student′s application.

Call a function procedure to determine and


return the APS score for the student. The
three marks already entered must be sent
to the function procedure as value
parameters and the marks for the next
three best subjects (excluding Life
Orientation) must be entered in the
function. The APS score must then be
determined and returned.
If the student has Mathematics, call a
subprocedure to determine whether the
student qualifies for the general first year,
foundation year or does not qualify at all.
Decide on your own parameters and
types.
If the student has Maths Literacy, call a
function procedure to determine whether
the student qualifies for the foundation
programme.
Display a suitable message about the
application status of the prospective
student. The message should include the
student name, reference number and APS
score. If not accepted, the reason should
be provided.
4.6. You are the bookkeeper for a retail
company that bought stock from 25
suppliers during the past month. The
amount paid to the suppliers included 14%
VAT. To determine the selling price you
increase the cost price of the stock by
37.5%.
Do the planning and then write an
algorithm to display a report of the
amounts paid to the various suppliers. Also
display how much the company must pay
to the Receiver of Revenue (SARS). The
algorithm must contain the following:
• All input is done in the main
procedure.

• A subprocedure must divide the


amount payable to each supplier into
the basic amount and the VAT amount.

• A function must display the basic


amount and the VAT amount for every
supplier.
• A function must calculate the selling
price (selling value) for the goods
received from each supplier.

• The first subprocedure must also


divide the selling value into the basic
amount and the VAT.

• A function must receive the VAT


amount on the cost price, the VAT
amount on the selling price, and a total
for the VAT payable to SARS. It will
calculate the difference between the
VAT amounts and accumulate these
differences for the 25 orders in the VAT
total.

• The total amount that must be paid to


SARS must be displayed in a function
at the end of the algorithm.
Chapter 10 Sequential text
files

Introduction
A file is a collection of data stored
under a common name. Up to now,
we’ve used data that is entered on the
keyboard and stored in temporary
locations, such as an array. Data in a
file is usually stored on a more
permanent medium such as a disk or
CD. Frequently, the nature of the data
is also more permanent, for example
the data of all the employees
employed by a company.

The way that data is stored in a file


determines the type of file it is.
Although there are various types of
files, we’ll discuss sequential access
files, sometimes also known as text
files. The characters in a sequential
access file are stored in a sequential
manner, one record after another.

Because the information in the file is


stored in sequential order, it can only
be accessed sequentially. For
example, the user will have to read the
first four lines of text before the fifth
line can be accessed.

Outcomes
When you have studied this chapter, you should be able
to:
understand what a sequential file is,
understand the difference between input and
output files,
do the following in pseudocode:
• open an input file to read text from it,

• open an output file to add text lines to it,

• create an output file with text lines,

• test whether a sequential access file


exists,

• close a sequential access file,


• read information from a sequential
access file,

• test for the end of a sequential access


file, and

• update values in a sequential file by first


reading the records into an array.

1 Input and output files


The difference between input and output files is based
on the way these files are used and accessed.

An input file contains stored data that can be specified


as input to a program when read from the file during
processing.

An output file is used by a program to store new data,


by writing it to the file. When dealing with sequential
files, a “new” file is always used because the changed
or newly created data must be written or rewritten from
the first to the last line of text.

The file pointer will indicate the position in the file


where text must be read or written.

It is not possible to write data to a specific position


within existing data in an input file, but more data can be
added after the existing data. This is called appending
data.

Every file is identified by an external file name, such as


marks.txt or profit.txt.

2 Opening a sequential
access file
Every file that is used in the program must be opened
before it can be used. The open statement, which
contains the name of the file, will try to find the
specified file. When the file is found, it will connect this
external physical text file to the filename used in the
program in order to use it in the program.

As discussed in the previous paragraph, there are input


files, output files and output files to append data to. The
programmer has to specify in the open statement what
type of file must be opened.

In the generic programming (where we do the planning)


the following open statements will be used:

Input file
open input(name of file)

Example: open input(employees.txt)

The file pointer is now placed at the beginning of the file


to start reading at the first line of text.

Output file
There are two ways to open an output file. It can
either be opened to create a new output file or
an existing file can be opened to append new
text lines to it.

open outputCreate(name of file)

Example: open outputCreate(employees.txt)

This statement will create a new, empty


sequential access file. The file pointer is now
placed at the beginning of the file to start writing
the first line of text.

open outputAppend(name of file)

Example: open outputAppend(employees.txt)

This statement will add new lines of text to an


existing sequential access file. The file pointer
will be placed at the end of the file. With every
write statement, new lines of text will be added
to the file.
When a specified input file doesn’t exist, the
program ends abnormally, so it’s good
programming practice to test to see whether the
file exists before trying to open it to read its
data.

A suitable action must be taken if the file does


not exist, for example:

3 Closing a sequential
access file
A file should be closed as soon as possible to prevent
loss of information. In the case of an input file, it must
be closed as soon as all the text has been read from it
and, when using an output file, as soon as all the text
has been written to it.
In cases where quite a number of files are used at
different stages in the program, it is very important to
adhere to this rule by keeping open only the files that
are in use. It is also essential that files are opened just
before their data is needed, and not before.

In the planning of a program, the statement used to


close a file is:

close(name of file)

Example: close(employees.txt)

4 Reading information from


a sequential access file
As mentioned earlier, a sequential access file is always
read from the beginning of the file. The open statement
positions the pointer before the first character of text.

The read statement enables the program to read one


line of text at a time, until the newline character is
found. However, the string that is returned when the line
is read doesn’t contain the newline character.

Lines can be read from a file until the end-of-file (eof)


character is found, which indicates that the file doesn’t
contain any data that has not been read.

The statement in an algorithm to read a line of text from


a file is:

read(name of file)

The line of text is normally placed into a string variable


from where it can be used for further processing.

Example: EmployeeData = read(employees.txt)

In an algorithm, the word eof indicates that the end of


the file has been encountered, so processing must stop
and the file must be closed.

Example 1
In this pseudocode example, lines of text are read from
the employee file. Every line of text is then displayed.
The process is repeated until the end of the file is
reached.
Note that the first line of text is read before the loop.
The current line of text is displayed inside the loop, and
the next line of text must be read before the next
execution of the loop. If this next read statement is
omitted, the first line of text will keep on being displayed
because the next line is never read and the end of file
will never be encountered. Each read statement
accesses the next line of text and tests whether the end
of the file has been reached.

The statement EmployeeData = read(employees.txt)


took a complete record from the file and read it into the
variable called EmployeeData. This line of text can
consist of many different fields separated by special
characters, called delimiters. String manipulation
statements would first be necessary to divide the line of
text into different variables before the individual values
can be used.

The records in the file could be:


12345*Boyd.R.S.*Sales*Manager#

23456*Nkosi.S.A.*Purchases*Assistant#

33445*Pillay.N.*HR*Assistant#

41231*Mokoetsi.M.M.*Marketing*Officer#

The record EmployeeData contains four fields – the


employee number (empNum), employee name
(empName), department (empDept) and the job
description (empJob).

After the first record has been read, the variable


EmployeeData will have the value
“12345*Boyd.R.S.*Sales*Manager#”. We would then
want to get the employee number, employee name,
department and job description separately. It can be
clearly seen that fields are separated by an asterisk
and that a hash sign indicates the end of the record.

Various string manipulation statements exist in different


programming languages to find the position of the first
“*” in the string. The substring up to that position can
then be placed in the variable called empNum resulting
in empNum = 12345. These values can then be deleted
from the beginning of the original string up to the point
of the first delimiter. The string now contains the value
“Boyd.R.S.*Sales*Manager#”. The process can be
repeated to place the value “Boyd.R.S.” into empName
and the value “Sales” into empDept. Lastly, the value
“Manager” will be placed into empJob and when the # is
encountered as a delimiter, the process will stop for the
current record.

This string manipulation process enables the


programmer to have access to the individual variables
empNum, empName, empDept and empJob. The
programmer can now use them in processing e.g. to
display them on the screen of the computer.

The string manipulation and division into separate


variables could typically be done in a subprogram and
the hierarchy chart is provided. The algorithm for the
main modules is also provided – you can see that it is a
modification of the previous algorithm.

Figure 1 Hierarchy chart for MainModule algorithm


Because string manipulation is not covered in this book
in detail, the code for the sub procedure is not provided.

The output for this piece of code could be as follows:

EMP EMP NAME DEPARTMENT JOB


NUMBER DESCRIPTION

12345 Boyd.R.S. Sales Manager

23456 Nkosi.S.A. Purchases Assistant

33445 Pillay.N. HR Assistant

41231 Mokoetsi.M.M. Marketing Officer

:
5 Writing information to a
sequential access file
As mentioned earlier, text lines can be added to an
existing file or a new output file can be created. The
open statement indicates the way to write to the file.

In both cases, the write statement enables the program


to write one line of text at a time. The new line
character (indicating the end of a record) will not
automatically be written to the file, so when the
programmer wants the next string of text to be written
on a new line it must be specified.

Lines of text are usually also written in a loop, so when


the end is reached the programmer can simply close
the file.

The statement in an algorithm to write a line of text to a


file is:

write(name of file)

The line of text is normally written from a string variable.


This can be indicated in an algorithm by specifying the
word from followed by the variable name.

Example:write(employees.txt) from EmployeeData


In an algorithm, an additional write statement must be
included if the new line character must also be written.
If it need not be written, this additional write statement
can be ignored:

write new line

Example 2
In this pseudocode example, employee data will be
accepted from the keyboard and written to a new text
file. When the user indicates that there are no more
employees, the process will terminate and the file will
be closed. Every line of employee data must be written
to a new line in the file.

Once again, the first line of text must be entered before


the loop. It is written to the file in the loop, and the next
line of text must be entered before the next execution of
the loop. In this example, a value of -1 indicates that the
loop must be terminated and the file be closed.

In Example 2, we assumed that users would enter the


values by including all fields for a record, separated by
delimiters. However, this is not user friendly and is also
prone to input errors, so it would be better to let the
user enter each value per employee, then use string
functions to combine it into the correct format before
writing the record.

Most computer languages have a concatenation string


function, which combines several values into one line of
text.

In our case, the user could enter the employee number,


the employee name, the department and the job
description into the variables empNum, empName,
empDept and empJob respectively.

Then the following statement could be used:

Our algorithm could be changed, as follows:


The file will be created containing the following records:

12345*Boyd.R.S.*Sales*Manager#

23456*Nkosi.S.A.*Purchases*Assistant#

33445*Pillay.N.*HR*Assistant#

41231*Mokoetsi.M.M.*Marketing*Officer#

:
6 Reading from and writing
to the same sequential file
If lines in a sequential file need to be modified, the only
way to do this is to read all the records into an array,
manipulate the array elements, then write the array
back to the file by recreating the file.

Example 3
Let’s say we need to change either the job description
or department of particular employees.

Initial planning

Step Read the entire file


1: into an array

Step For all employee


2: data that needs to
be changed

Accept the
employee number

Check if it exists in
the array

Ask if job
description must be
changed

Ask if department
must be changed

If job description
must be changed

Accept new job description

Replace existing job description in the


array for the employee data that needs
to be changed

If department must
be changed

Accept new department name

Replace existing department in the array


for the employee that

needs to be changed

Step Create a new file


3: from the array
Figure 2 Hierarchy chart for Example 3

Note that the code for the GetFields() subprocedure is


not provided because detail string manipulation
techniques are not covered in this book.

Algorithm
Exercises
1. Indicate whether the following statements are
true or false. Provide a reason for your answer.
1.1. An input file should be closed as soon
as all data has been read from it.
1.2. It is possible to write data to a
specific position within other data in an
input file.
1.3. Every file that is used in the program
must be opened before it can be used.
1.4. In an algorithm to read data from a
file, the following code is correct:

1.5. It is impossible to modify existing


values in a text file.
1.6. The data in a sequential access file is
always accessed in consecutive order
from the beginning of the file to the end.

2. Provide a hierarchy chart and an algorithm for


each of the following. It is not necessary to
include the code for the sub procedures where
string functions are used to break each line into
positions in the array.
2.1. A file called “diary.txt” contains first
names, surnames, e-mail addresses and
telephone numbers for 100 people in the
following format:
Freddy, Gomes,
[email protected],0824154433.
Some of the e-mail addresses and
telephone numbers need to be changed.
You can assume that the file already exists
and that there will be exactly 100 text lines
in the file.
2.2. The file C:\Employee.txt contains a
text line containing the following
information for each employee in a
company:
Employee number
Name
Gender
Department code
Annual salary

Values are separated by dollar ($) signs


and the end of each line is indicated by an
at (@) sign.
All the employees in Department A
received a 6.5% increase. Update the
salary for each of these employees.
2.3. Using the file used in 2.2, append new
employees to the end of the file. For each
new employee, enter the employee
number, name, gender, department and
annual salary. Validate that the department
is only one character in length, that the
gender is only F or M and that the annual
salary is a decimal value greater than 0. If
any of the input data is not correct, display
a suitable error message and keep on
entering the value until it is correct.
2.4. Create a file with a line per student
containing the following data for any
number of students:
Student number
Student name
Test mark 1
Test mark 2
Test mark 3

Only valid values can be accepted and all


fields in the file must be separated by hash
(#) signs. The end of a line must be
indicated by an asterisk.
Chapter 11 Introduction to
object-oriented
programming

Introduction
The art of software development is
one of the most difficult challenges
undertaken by humankind. To
complicate matters, computer
hardware is constantly being improved
in terms of speed and capacity.

The more hardware enables us to do,


the more we want it to do, so the more
complex problems and software
solutions become.

It is because of this complexity that we


are constantly looking for new
strategies to simplify the software
development process. Object
orientation is such a strategy. The
object-oriented approach is a different
way of thinking about computation and
problem solving. People often use this
form of thinking to address problems in
everyday life, which makes object
orientation a natural approach to
problem solving and easy to grasp.

In the procedural approach to problem


solving, we focused on processes and
procedures. In the object-oriented, or
OO, world, we focus on the data, its
properties or attributes, and
responsibilities, and how it interacts
with other parts of the system. As a
result, information is structured
differently within the computer.

A system developed using the object-


oriented approach typically consists of
a collection of objects that
communicate with one another to
solve a problem. You could say that
object-oriented systems are defined
using objects.
One of the great advantages of the
object-oriented approach is that it
makes it easy to re-use objects. We’ll
discuss re-use in more detail later in
this chapter.

Some programming languages that


use object orientation are:

C++
Delphi
Smalltalk
Java

Outcomes
When you have completed this chapter, you should be
able to:
understand the basic concepts of object
orientation,
understand the importance of encapsulation
and information hiding,
distinguish the relationships between classes,
and
follow the basic steps of object oriented
design.
1 Concepts of object
orientation
Most of the concepts in procedural languages also
feature in most OO languages. Sometimes an OO
language may refer to a familiar concept in a different
way, but it will still be the same concept. For example,
variables, procedures, invocation of procedures and
passing parameters to and from procedures are
concepts common to both types of programming
languages. Control structures like sequence, selection
and iteration structures also feature in OO languages.
However, in object orientation there is a whole new set
of concepts, which we’ll introduce now.

1.1 Objects
The real world is full of objects, such as motor cars,
dogs, cities, people, customers, cash registers, and so
on. We can also consider an object to be a container
for data, with attributes, and the operations needed to
manipulate that data. Objects function well as software
modules because they can be created, used and
maintained independently of one another.
Figure 1 shows an object with properties, or attributes,
and operations, or methods.

Figure 1 An object with properties and operations

For example, consider a motor car object. Typical


attributes for such an object might be fuel consumption,
speed, power and engine size. Possible operations
might be stop, accelerate, change gears and reverse.
Typically, the speed of the motor car is not modified
directly, but will be modified by, for example, the
accelerate operation. The accelerate operation, in turn,
will modify the speed data, or value of the speed
attribute. From this it is clear that we use operations
primarily to change the data of an object.

All the objects we’ve considered so far contain tangible


things. However, there are other kinds of objects in the
real world that aren’t tangible, such as roles, incidents
and interactions. For example, roles can include
lecturer, student and pilot; cycle race or political
meeting would be an incident; and interview and
conversation would be interactions.

Table 1 shows examples of the characteristics of an


object.

Table 1: Characteristics of the object human being


Characteristics Examples

Are abstractions, concepts Human being


or things

Have clear boundaries Human being knows his or her physical


capabilities

Are found in the problem References to use for species


domain

Know things about Height, weight


themselves

Interact with other objects Interact with other humans and things

1.2 Properties
Objects often need to hold information about
themselves. Let’s use an object called Bob as an
example. Bob needs to know his name, age, gender,
and so on. We refer to these items as the object’s
properties or attributes. Each of these properties
normally has a scope, a type and a value, just as
variables in the procedural approach do. The scope of
an attribute can be private or public. An attribute that
has a private scope is visible only inside the object it
applies to. This means that the private attributes of an
object are not visible to other objects within the same
system. A property that has a public scope is visible
within the object it applies to as well as to other objects
within the same system.

Table 2 shows some of the properties, both private and


public, of the object called Bob.

Table 2: Properties of Bob


Property Name Scope Type Value

Name Public String Bob

Age Private Integer 23

Gender Private String Male

Weight Private Integer 82

Height Private Real 1.86

Every property, like a variable, has a type. Property


types are normally simple types, such as string, integer,
real, and so on. Note that a property can also be
another object. We refer to the state of an object as the
values of all the properties of that object at a specific
time. For example, in Table 2 the Value column reflects
the state of the object called Bob.

1.3 Operations
Objects communicate with one another by sending
messages. Consider the objects car and driver. In order
for the driver to use the car, the driver object needs to
send the message to the car object to start and drive
the car. This requires the car object to be able to
receive the message.

We refer to these messages as the operations or


methods of an object. These messages are defined in
the receiving object. Operations are similar to the
procedures and functions that we used in procedural
solutions. We also refer to the messages that an object
can receive as the services provided by one object to
another.

An operation in an object has a unique signature


consisting of its name, optional parameters and optional
return values. This concept is similar in procedures and
functions.

Similar to properties, operations also have scope, which


can be private or public. Operations with private scope
are visible only to the object in which the operation is
defined, and operations with public scope are also
visible to other objects within the system. The collection
of operations in an object is sometimes referred to as
the behaviour of the object. The driver object only has
access to all the public attributes and methods of the
car object. Some of the attributes of the car object are
hidden to the driver, such as engine and the gearbox.

1.4 Classes
An object is an instance of a class. We can create one
or more objects from a single class. This makes a class
a sort of template or pattern. A class defines the basic
characteristics and behaviour – properties (attributes)
and operations (methods) – that are available to all
objects in that class.

The action of creating an object from a class is referred


to as the instantiation of an object. When an object is
instantiated, it receives all the attributes and operations
of its class. If there is more than one object belonging
to the same class, their states may be different. This
means that, except for sharing a similar structure,
objects of the same class are completely independent.

Consider a class called Car and two instances of this


class, as shown in Table 3.
Table 3: The class called Car, and two instances of
the class
Class: Car

Attribute Name Type

Type String

Make String

Model String

Colour String

Object: Car Object: Car

Attribute Name Type Attribute Name Type

Type Passenger Type Passenger

Make Audi Make VW

Model A4 Model Polo

Colour Blue Colour White

You can see that the two instances of the class Car
have the same attributes, but different values.

2 Encapsulation and
information hiding
In the object-oriented approach, classes, and therefore
also objects of that class, are similar to black boxes
with a clearly defined interface. This interface is the
only mechanism that other objects can use to
communicate with the object.

We say that inside a class, behind the interface, the


data and the implementation of the operations are
encapsulated or enclosed in a capsule. This makes the
internal workings of a class invisible to all other classes.
This is a good technique, since there is no need for
other classes to know the internal structure of this
class, in other words, how it represents its data and
how it performs its operations. We call this
encapsulation information hiding.

Figure 2 shows an object receiving a message from


another object via its interface:
Figure 2 An object receives a message from
another object

We hide information within a class by making some


properties and operations private. We make only the
properties and operations that can be manipulated by
other classes public. The collection of these public
attributes and operations forms the interface of a class.
Because other parts of the system can interact with an
object only through its interface, the other parts of a
system cannot accidentally change private property
values in an object. This means that information hiding
makes objects more robust.

By hiding information we can change the implementation


of a class without affecting other classes that rely on it.
We achieve this by not changing the interface on which
other classes rely. The opposite is also true. Changes
to other parts of a system will not affect the internal
workings of this class. As a result, information hiding
ensures the independence of classes and objects.

Because information hiding makes objects more robust


and independent, they are easily re-used in the object-
oriented approach. Once we have defined a class, we
can re-use it, or instantiate it, in other parts of a
system, and even in other systems. The independence
of classes also reduces the impact when we have to
make corrections and changes to a system. As a result,
the cost of corrections and changes tends to be lower.
Consider a class called Sorter, which sorts a list of
integers. The interface of the Sorter class consists of
one operation named Sort. Sort accepts a list of
integers as a parameter.

Table 4: The class called Sorter

Class: Sorter

Attributes

Operations

Public Sort (pIntegerList : Array of integers)

Now suppose the Sort operation (method) uses the


bubble sort algorithm to sort the list of integers. This
doesn’t work well, so the programmer has to change it
to use the quick sort algorithm. To make the change,
the programmer only has to re-write the Sort operation.
The interface stays exactly the same, so the classes
whose objects use objects in the Sorter class don’t
need to be changed.

3 Design notations
Three people who have done a lot of work in the OO
design notation area are James Rumbaugh, Grady
Booch and Ivar Jacobson. At first, each of them had
their own method of representing an OO design. Not
only were the representations different, the underlying
theories of object behaviour and interaction were also
different. A couple of years ago, Rumbaugh, Booch and
Jacobson conceived of the Unified Modelling Language,
or UML. UML enables the designer to represent
classes, with their attributes and operations, as well as
the relationships between classes.

4 Relationships between
classes
The relationships between classes fall into three
categories:

association,
aggregation, and
inheritance.

Let’s consider each of these categories.

4.1 Association
We’ve already said that objects communicate with one
another in that one object uses the services of another.
This implies some form of dependency between objects
and, consequently, the classes to which these objects
belong.

An association expresses the relationship between two


classes. Note that association is found at the class
level. We can identify associations during the analysis
phases of the problem by looking for verbs in source
documents. For example, if we read, “An Employee
works for the company”, we can deduce that there is an
association between the employee and company
classes.

There are different kinds of associations between


classes. A relationship can be one to one, one to many
or many to many.

Consider the classes Parent and Child. A parent might


have more than one child and a child can have two
parents. Therefore the association between the Parent
and Child classes will be many to many, or more
specifically, two to many.

Figure 3 shows an example of an association.


Figure 3 The association between Employee and
Company classes

4.2 Aggregation
An aggregation is a specific form of association, and is
not an independent relationship. In an aggregation, one
class is part of another class. This type of relationship
is often referred to as a “part-of” relationship. Note that
the class that is a part of another class can exist only
as part of the container class, so it cannot exist
independently. Note also that, like association,
aggregation works at the class level not the object
level.

Consider a car, which consists of a body, wheels,


windows, and so on. There are thus relationships
between the motor car and its components. More
specifically, an aggregation relationship exists between
the car class and the body, wheel and window classes.

Figure 4 shows an example of an aggregation.


Figure 4 The aggregation relationship between car
class and body and wheel classes

4.3 Inheritance
Inheritance is the third type of relationship between
classes. Inheritance between classes takes the form of
a tree structure linking a super class to its subclasses.
All subclasses inherit the characteristics of their
associated super class.
For example, consider the classes, vehicle, motorbike,
truck, and car.

A motorbike, truck and motor car are all different types


of vehicles. So we can have a class called vehicle and
have the classes motorbike, truck and car as
subclasses of the vehicle class. We say that a super
class generalises its subclasses. A subclass is a
specialisation of the super class.

We can extract behaviour common to different classes


into a common super class. For example, if the three
subclasses, motorbike, truck and car, all have a
property number of wheels, we can remove it from the
subclasses and add it to the super class, vehicle.

Figure 5 will help you to understand inheritance, where


you can see that the motorbike, truck and car classes
inherit all the attributes from the vehicle class.
However, motorbike has a unique attribute, stroke. The
same applies to the operations: truck has two special
operations, load() and unload().

Inheritance is a type of relationship that we often refer


to as a “kind-of” relationship. It is another aspect of the
object-oriented approach that allows us to improve re-
use. In the vehicle example, if we want to create a bus
class, we can create it as another subclass of the
vehicle class. This means that all the properties and
operations defined in the vehicle class are automatically
defined in the bus class. All that remains is to define the
properties and operations specific to the bus class.

Figure 5 Inheritance between a super class and


subclasses

It is also possible for a subclass to inherit from more


than one super class. This is referred to as multiple
inheritance. Not all programming languages support
multiple inheritance. When you use the object-oriented
approach to solve a problem, use inheritance, and
especially multiple inheritance, sparingly, as the
relationships can become quite complex.

5 More concepts
This chapter is a basic introduction to OO, but you
should know that there are some advanced concepts
that we have not covered here. These include abstract
classes, polymorphism, overriding and overloading.

6 Designing an object-
oriented solution
The object-oriented approach is about far more than
just a couple of new programming structures and
techniques. As we mentioned before, it’s a whole new
way of thinking. This means that objects are not only
part of the programming of a system but are used right
from the start during the analysis and design phases.

Here are some basic steps to follow when solving a


problem using the OO approach:
1. Read the problem statement and identify
classes.
2. Look for properties and methods that apply to
the classes identified.
3. Determine the relationship and interaction
between classes.
4. Design the algorithms for the methods using
structured design.
5. Develop the main algorithm.

You can see that the whole approach to designing a


system is different. Now try some problems.

Exercises
1. Explain the difference between a class and an
object.
2. List some of the advantages of object orientation.
3. Assume we have a class called dog. Name three
possible attributes and three possible operations
for this class.
4. Assume we have a class called bicycle. Name
four possible attributes and three possible
operations for this class.
5. A retail company needs an ordering system to
keep a record of orders per customer. For each
customer, there is a delivery address, which has
to be maintained. Each order consists of order
line items. For an order line item, the company
needs the item code and quantity that the
customer ordered. Identify classes for this
problem. Define attributes and operations for
each of the classes you identify.
6. A soccer club requires a system that can be used
to keep track of its teams and the players in
each team. Currently the club has four teams, A,
B, C and D. The club needs basic information on
each player, such as first name, surname, age,
date of birth, weight, height and the position in
which they play. The club needs to be able to
change a player’s position, add a player to or
remove a player from a team, and assign a team
to a match.

For each team, the club wants to know the number of


games played and the number of games won. In
addition, the club wants to keep track of matches,
where they are played, which teams play which
matches and when they play them.

Identify classes for this problem. Define properties and


operations for each of the classes you identified. Then
identify relationships between the classes.
Appendix A Tools for
planning programs

Introduction
Pseudocode has been discussed and
used throughout this book when
planning programs. There are,
however, different methods that can be
used when representing an algorithm.
We’ll briefly discuss the use of
flowcharts and Nassi-Shneiderman
methods.

First we’ll write the algorithms for


solving two problems in pseudocode,
we’ll repeat the process using
flowcharts, followed by a Nassi-
Shneiderman diagram.

1 Pseudocode
Example 1
Write an algorithm to enter two numbers that are not
equal and display the bigger number.

Example 2
Write an algorithm to enter integers between 5 and 20
and accumulate their sum until it exceeds 200. Display
how many integers were entered.
2 Flowcharts
A flowchart is a schematic representation of an
algorithm. It illustrates the steps in a process and it
consists of a number of specific diagrams joined in a
specific manner. It graphically represents the program
logic by using a series of standard geometric symbols
and connecting lines. Different flowchart symbols are
used for different aspects of the process.

Flowchart symbols

The following symbols are used:

Table 1: Flowchart symbols


Symbol Description

Terminal
This symbol indicates the starting or stopping point in the
logic. Every flowchart should begin and end with this
symbol.

Input/Output
This symbol represents an input or output process in the
algorithm, such as reading, writing and displaying.

Processing
This symbol is used for types of processing, such as
arithmetic statements and assigning values.

Decision
This symbol is used to compare variables/values that may
change the flow of the logic. It may cause the logic to
branch in another direction.

Module
This symbol represents another module that must be
processed. This module will have its own flowchart.

Connector
The connector joins two parts of the flowchart, e.g. from one
page to the next page.

Connecting lines
These lines connect flowchart symbols with one another.

Example 1
Draw a flowchart to enter two numbers that are not
equal, and display the bigger number.
Figure 1 Flowchart for Example 1

Example 2
Draw a flowchart to enter integers between 5 and 20
and accumulate their sum until it exceeds 200. Display
how many were entered.
Figure 2 Flowchart for Example 2

3 Nassi-Shneiderman
diagrams
A Nassi-Shneiderman diagram (or NSD) is a graphical
representation for structured programming. Developed
in 1972 by Isaac Nassi and Ben Shneiderman, these
diagrams are also called structograms, because they
show a program’s structures. Everything you can
represent with a Nassi-Shneiderman diagram you can
also represent with a flowchart.

Symbols used to construct


a Nassi-Shneiderman
diagram

Process block
A process block represents the simplest of steps. When
a process block is encountered, the statements within
the block are processed. When the statements have
been processed, processing proceeds to the next
block.

Decision block
This block enables the programmer to include a
condition in the diagram, which will produce different
branches or paths for true and false processing.

Iteration block
An iteration block allows the programmer to repeat a
block of instructions a number of times while a specific
condition is true or until a specific condition is true.

Now we’ll draw Nassi-Shneiderman diagrams to solve


our two problems:

Example 1
Draw a Nassi-Shneiderman diagram to enter two
numbers that are not equal, and display the bigger
number.

FindTheBigger
Figure 3 Nassi-Shneiderman diagram for Example 1

Example 2
Draw a Nassi-Shneiderman diagram to enter integers
between 5 and 20 and accumulate their sum until it
exceeds 200. Display how many were entered.

CountTheNumber
Figure 4 Nassi-Shneiderman diagram for Example 2
Appendix B Error handling
and debugging techniques

Introduction
Beginners aren’t expected to write
flawless programs! The best way to
learn to program without errors is to
practise, practise and, once more,
practise. It is said that practice makes
perfect!

There are, however, techniques that


can assist programmers to find errors
in the logic.

Outcomes
When you have studied this appendix, you should be
able to:
distinguish between different types of errors
and
use a trace table to test the correctness of
the program logic before the program is
coded in a programming language

1 Types of errors

1.1 Syntax errors


At the moment you’re reading an English sentence, in
which the rules of the English language have been
followed. If you read the sentence “The boook have
many pages.”, you would immediately see two syntax
errors: the word “book” was incorrectly spelt, and the
word “have” should have been “has”. These errors are
syntax errors. They violate the rules of English
grammar.

Computer programs are written in programming


languages, each of which has specific rules that must
be taken into consideration. Even though we’re only
doing generic work by planning programs, we also have
to adhere to specific rules, for instance spelling the
name of a variable exactly the same throughout an
algorithm.
1.2 Logical errors
Logical errors can sometimes be very difficult to
correct. In everyday life it is not possible to leave your
house before you’re dressed. This is not a logical way
to behave! Here’s a very simple example of a logical
error in an algorithm.

This algorithm contains an instruction that asks the


computer to add a variable called number to another
variable called total. But the programmer has forgotten
to ensure that the variable number has a valid value!
The instructions could have been the following:

total = total + number

enter number

These two instructions are in the wrong order!

1.3 Data errors


Data errors are usually found in the input data. We
have repeatedly tested input data in our examples to
ensure that valid values have been entered. For
instance, does the variable contain a numeric value, did
the user enter a valid character, and so on. Error
messages were displayed whenever incorrect data was
entered, and often the user was asked to re-enter the
data until valid data was entered.

2 Trace tables
A trace table can be used to test the correctness of a
program. There may be only a small error that isn’t
obvious. However, when a program is carefully
checked, the chances are very good that the output will
be correct. Trace tables were explained in earlier
chapters, but are repeated here. Let’s use an example
to illustrate this concept.

Write an algorithm to calculate the product of two


integers, the variables num1 and num2. Store the
answer in the variable product.

Algorithm
To create a trace table we need an instruction column,
a column for each of the variables and a column for the
output (which will be shown on the screen).

The instructions will be written in the first column in the


same sequence as in the program.

To test the program, we’ll use num1 = 4 and num2 = 5.

Table 1: The trace table for CalcProduct


Instruction num1 num2 product Output

display Enter the first integer

enter 4

display Enter the second integer

enter 5

calculate 20

display The product is 20

This method is also called desk checking, because it is


done before the program is written in programming
language.

Let’s do a second example that contains selection


statements, to show how these types of statements
should be included.
The programmer must plan a program to sell tickets for
a show to customers. The price of a ticket is R30, but if
a customer buys from 10 to 20 tickets, the price per
ticket is only R28. The price for more than 20 tickets is
R25 per ticket. The customer must enter the number of
tickets he or she wants, then the program must display
the amount due.

We need to include another column in the trace table to


show the outcome of the if statement.

Algorithm

Now we’re going to test this algorithm using 20


as the number of tickets.

Table 2: The trace table for BuyTickets


Instruction noTickets amtDue Outcome Output
of If
display How many
tickets do you
want to buy?

enter 20

if False

if False

calculate 500

display The amount due


for 20 tickets is
R500

This answer is incorrect! When a person buys 20


tickets, the price is R28 per ticket and then the amount
due must be R560.

When we study the if statements, we notice that the


second if statement should be:

if noTickets <= 20 instead of if noTickets < 20.

The correct algorithm will now be:


You can redo the trace table using other values to test
the algorithm to ensure that the program will produce
the correct answers. It is quite important to test your
algorithm in this way for correctness.

Exercises
Write the algorithms and then create trace tables for
each of the problems to test the algorithm for
correctness.

1. Enter the temperature in degrees Fahrenheit (F)


and convert it to degrees Celsius (C) using the
following formula:
9C = 5(F – 32)
Display the temperature in Fahrenheit and
Celsius. Test the algorithm using 32 °F and 212
°F. The answers should be 0 °C and 100 °C.
2. Enter two numbers. If the numbers are equal,
increase the sum of the two numbers by 20%,
but if the first number is less than the second
number, calculate the difference between the two
numbers. If the first number is greater than the
second number, decrease the product of the two
numbers by 25%. In each case, store the answer
in a variable called answer. Display the value of
answer on the screen. Test the algorithm using
the numbers 12 and 5, 4 and 8, and 7 and 7.

In each case, calculate the answers beforehand to


ensure that your algorithm produces the correct
answers.
Glossary
Accumulation
Accumulation is used in problem solving to calculate
a total or an average. When you add 1 to the
accumulator during every execution of the loop, the
accumulator is called a counter.
Accumulator
A variable that acts as a register to store the results
of an accumulation process.
Aggregation
In terms of the relationships between object
classes, aggregation occurs when one class is part
of another class.
Algorithm
A set of instructions written in a specific sequence to
solve a problem.
Argument list
The list of variables in the call statement that
correspond to the list of parameters in the function
or subprocedure.
Array
Variables of the same data type grouped under a
single name.
Array element
A single variable in an array that can contain a value
at a given time.
Association
An expression of the relationship between two
object classes.
Boolean variable
A variable that can take only one value, true or false.
Bubble sort
A sorting method in which elements in an array are
compared to each other in pairs; when an element is
not in sequence, it trades places with the other
element until all elements are sorted in the required
sequence.
Character
A single number, letter or special character; any one
stroke that can be typed on a keyboard.
Character variable
A variable that contains a single letter, number or
special character,
Compound If statement
A statement used to test more than one condition
before the result can be evaluated to be either true
or false.
Class
A construct used as a template to create objects
that have predefined properties.
Constant
A fixed value that cannot change throughout the
entire program; may be any data type.
Data
A collection of facts, such as values, measurements,
or readings.
Database
A number of related files or tables.
Data errors
Incorrect data that causes a program to cease
processing or provide incorrect results.
Data processing
A sequence of operations performed on data to
generate information.
Data validation
A test to check that input data can be used by the
program in its current format.
Data warehouse
The largest structure used to collect and store data
for processing, analysis and reporting; may consist
of several databases.
Encapsulation
Also known as information hiding, a technique that
makes the internal workings of a class invisible to all
other classes.
End-of-file character
A character used to signal that the file doesn’t
contain any data that has not been read.
Field
Also known as a data item, a field is a number of
characters or a name.
File
A collection of related records organised and stored
in a specific way.
File pointer
Indicates the position in the file where text must be
read or written.
For loop
Also known as a fixed count loop or an automatic
count loop, a statement used when the number of
iterations of a set of instructions is known.
For-next loop
Used to repeat a section of code a number of times
with a control variable that has a differing value each
time through the loop.
Function call
A statement that activates or calls a function from
another part of the algorithm.
Function header
The first line of a function, which contains the word
function, a function name and a possible list of
parameters.
Function procedure
Instructions that perform a specific task that is often
repeated are coded separately so that they can be
reused whenever required.
Hierarchy chart
A diagram that provides a global view of the
modules in a program, showing how they link
together to function as a complete program.
If statement
An instruction that controls program flow by allowing
a section of code to execute only when a specified
condition is true.
If-then-else statement
An If statement that specifies two actions: one
action to take when the specified condition is true
and another action to take when the condition is not
true.
Index
Also known as a subscript, an indicator of the
position of an element in an array.
Information
The result of data processing.
Inheritance
As a relationship between object classes, the
passing of characteristics from super classes to sub
classes.
Input
The data entered into a system for processing into
output.
Input file
Stored data that can be specified as input to a
program when read from the file during processing.
Integer variable
A variable that contains a whole number that has no
fractional or decimal part; the number can be
positive, negative or zero.
Intermediate variables
Variables used in a solution to help with the
calculations.
IPO chart
An Input/Processing/Output (IPO) chart, which
enables programmers to do comprehensive
planning; the Input and Output columns contain only
variable names, and the Processing column provides
an overview of the steps.
Iteration
Also known as looping, a type of programming used
when sets of instructions are repeated a number of
times.
Logical error
An error resulting from faulty reasoning; a bug in a
program that causes it to terminate abnormally or to
produce incorrect output.
Logical operator
An operator that joins two Boolean expressions to
yield a Boolean result, either true or false.
Modularisation
The division of a program into smaller pieces called
modules to improve flexibility and shorten
development time.
Nested If statement
One or more If statements contained within another
If statement.
Nested loop
A loop contained within another loop.
New line character
The new line character indicates the end of a record
in a file.
Object
A container for data, with attributes, and the
operations needed to manipulate that data.
One-dimensional array
The simplest form of an array, consisting of one
column of elements.
Operator
A symbol used in an expression or equation, which
tells the computer how to process the data.
Output
The result of processing input data.
Output file
A file used by a program to store new data by
writing to the file.
Parallel arrays
Two or more arrays that are related to one another
and have the same number of elements.
Parameter
Data in the form of variables or values that is sent to
a function or a sub procedure so that it can perform
the task it has to do.When dealing with a
subprocedure, a parameter may also contain the
address in memory to obtain and manipulate a
value.
Post-test loop
A Do-while loop in which the statements in the body
of the loop are processed at least once, and the
condition is tested only after the statements in the
body of the loop have been processed.
Pretest loop
A Do-until loop in which the condition is tested
before the statements in the body of loop are
processed.
Private scope
An object property that is visible only inside the
object it applies to.
Properties
The attributes of an object, each of which has a
scope, a type and a value.
Pseudocode
The way in which algorithm steps are written so that
they can be followed easily and understood.
Public scope
A object property that visible within the object it
applies to as well as to other objects within the
same system.
Real number
A variable that contains a positive or negative
number with a decimal part.
Record
A group of related fields.
Reference parameter
A parameter that is passed by reference to a
location in memory.
Relational operator
The operator used in a comparison between two
values, the outcome of which is always a Boolean
value.
Select case
Structures used to perform processing steps
depending on the outcome of a tested condition, in
which the same variable is tested for many different
values.
Selection sort
An array sort method that selects the smallest value
from the array and exchanges it with the first
element in the array, after which the second
smallest element is selected from the array and
exchanged with the second element; a process that
continues until the entire array is in a pre-specified
order.
Sentinel
A value that is not a legitimate data value and is
used to terminate a loop.
Sequential access file
Also known as a text file, a file in which the
characters and fields are stored in sequential order,
one record after another.
String
A variable consisting of two or more alphanumeric
characters.
Subprocedure
A separate procedure that consists of lines of code
to solve a specific part of a larger problem.
Subprocedure call
A statement that activates or calls a subprocedure.
Subprocedure header
The first line of a subprocedure, which contains the
word subprocedure, the subprocedure name and a
possible list of parameters.
Syntax error
An error in the grammar of a statement.
Table
A structure made up of rows and columns, in which
each row represents the data of one entity and each
column contains a category of data.
Trace table
Also known as desk checking or a walkthrough
table, a method of testing the logic of an algorithm
normally done prior to writing it in a programming
language.
Two-dimensional array
An array consisting of a number of rows and a
number of columns.
Value parameter
A copy of the value is passed to the function or
subprocedure as a parameter.
Bibliography
Erasmus HG, Fourie M & Pretorius CM 2002.
Basic programming principles. Sandton:
Heinemann.

Farrell J 2002. Programming logic and design


introductory. (2nd edn) Boston: Thomson
Course Technology.

Farrell J 2007. Programming logic and design


comprehensive. (4th edn) Boston: Thomson
Course Technology.

Farrell ME 2005. Learning computer


programming: It’s not about languages.
Hingham: Thomson Delmar Learning.

Robertson LA 2004. Simple program design.


(4th edn) Boston: Thomson Course
Technology.

Spranckle M 1992. Problem solving and


programming concepts. Hillsdale: Prentice
Hall International.
Vickers, P 2008. How to think like a
programmer (problem solving for the
bewildered). London: Cengage Learning.

You might also like