Basic Principles of Programmingtextbook PDF
Basic Principles of Programmingtextbook PDF
Basic Principles of Programmingtextbook PDF
The ability to clearly specify each step to create a problem-free computer program is a primary
skill needed by programmers. Basic Programming Principles 2nd edition guides beginner
programmers through the challenges of planning a computer program by presenting the 2nd Edition
The book aims to encourage beginner programmers to see all problems as challenges
and to seek all possible ways to solve these problems in the most effective, efficient and
economical way.
Correlie Pretorius and Hetsie Erasmus have been in tertiary education for more than 30 years
and understand the anxieties of beginner programmers and the abstract reasoning the subject
requires. It has always been their passion to encourage students to become logical thinkers
and to assist them to develop problem-solving skills. This book lays a solid foundation for
students who are being exposed to programming for the first time.
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.
ISBN: 9781775786030
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.
To copy any part of this publication, you may contact DALRO for information and copyright clearance. Any
unauthorised copying could lead to civil liability and/or criminal sanctions. Telephone: 086 12 DALRO (from
within South Africa); +27 (0)11 712-8000; Telefax: 086 6586 299; Postal address: P.O. Box 31627, Braamfontein,
2017, South Africa; www.dalro.co.za
Preface
•
•
•
•
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
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:
•
encouragement and assistance.
•
•
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.
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
The ability to clearly specify each step to create a problem-free computer program is a primary
skill needed by programmers. Basic Programming Principles 2nd edition guides beginner
programmers through the challenges of planning a computer program by presenting the 2nd Edition
The book aims to encourage beginner programmers to see all problems as challenges
and to seek all possible ways to solve these problems in the most effective, efficient and
economical way.
Correlie Pretorius and Hetsie Erasmus have been in tertiary education for more than 30 years
and understand the anxieties of beginner programmers and the abstract reasoning the subject
requires. It has always been their passion to encourage students to become logical thinkers
and to assist them to develop problem-solving skills. This book lays a solid foundation for
students who are being exposed to programming for the first time.
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. 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:
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.
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.
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.
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
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.
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.
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.
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.
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?
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.
Exercises
Complete the following table:
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”.
The first example, totalNumStudents = 20, means that 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.
Addition
Key words Examples
Increase by Increase the total by 12.
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.
Calculate the total of the first and the second sets of
Total 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 by The final mark must be decreased by 10%.
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 from Subtract 15 from the accumulated points.
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 words Examples
Of A quarter of 100 is 25.
Times The final mark is equal to all the marks times 1.5.
The wage is the hourly rate multiplied by the number of
Multiplied by
hours worked.
Calculate the product of the number of items and the price
Product of
per item.
By a factor of The total number must be increased by a factor of 12%.
Division
Key words Examples
Per Calculate the kilometres travelled per litre of fuel.
Out of 15 out of 60 is 25%.
If the ratio of girls to boys is 2:3 and there are 25 children,
Ratio
how many girls are there?
Divide the number of minutes by 60 to get the number of
Divide by
hours
Quotient of The quotient of 80 and 8 is 10.
Percent 50% percent of 250 ml is 125 ml.
Equals
Key words Examples
Is/are The sum of 20 and 12 is 32.
The difference between my age and my grandmother’s
Was/were
age was 60 years.
Will be The total of four numbers will be 300.
Equals The sum of 5 and 4 equals 9.
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.
After an increase of 10% the new calculated amount can
Replaced by
be replaced by the sales amount.
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:
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.
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.
Step 2: Multiplication and division are done from left to right (3*2=6):
5 – 9 \ 8 + 17 mod 6
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+5
9
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.
Note that (14 - 11) is executed before the other operations because it’s in
parentheses.
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 variables:
1. X = AB + C4
C − D − 5D
2. X = ______
E+5
3. X = 17BC − B(E − A)
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?
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?
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.
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.
Possible equations
~ Assume noOfItems contains a value
firstAmount = noOfItems * priceOfItem
amountDue = firstAmount – (firstAmount * discount / 100)
Exercises
Question 1
Complete the following table:
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 – bc2 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 copy-
ing 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 dis-
count of 5% on the amount due. Add 14% sales tax and then calcu-
late 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 bis-
cuits 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.
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.
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.
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.
Mail order A company that uses a catalogue or web page to advertise and
company sell items; once the customer has ordered and paid for an item, it
is posted to the customer.
Item in stock The item is available for purchase
Packaging and The cost of packaging the item and paying the postage. Also
posting cost called shipping costs.
To insure the The payment of an additional fee for which the company
parcel promises to refund the customer should the parcel not reach the
customer.
Dispatch date The date that the item will be posted
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 the
details 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 or
rejected insufficient funds
Credit card The amount will be deducted from the customer’s account and
debited with paid into the mail order company’s 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.
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.
or
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.
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.
From this, it is clear that the steps in an algorithm must always be written in
logical order.
• 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.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?
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.
Example:
You want to print a particular greeting to members of a forum.
Initial planning:
Obtain member status
If the member is new
Display standard new message
Else
Display message for registered members
Endif
GreetingModule
display “If you are visiting the forum for the first time, enter 1, else
enter 2.”
enter member
if member = 1 then
display “Welcome as a guest of this forum.”
display “To be able to access all features, you need to register first.”
else
display “Welcome as a member of this forum.”
display “You have access to the following features:”
display “Customise your profile”
display “Send personal messages”
display “Vote in polls”
endif
end
intMember = Convert.toInt32(txtMember.text)
If intMember = 1 Then
lblMessage.text = “Welcome as a guest of this forum.” & _
ControlChars.Newline & _
“To be able to access all features, you need to register first”
Else
lblMessage.text = “Welcome as a member of this forum” & _
ControlChars.Newline & _
“You have access to the following features:” & _
ControlChars.Newline & “Customise your profile” & _
ControlChars.Newline & “Send personal messages” & _
ControlChars.Newline & “Vote in polls”
End if
Example 8
Determine the weekly wage of an employee when the hours he has worked and
the hourly rate, are entered by the user.
CalcWage
display “How many hours did the employee work?”
enter hours
display “What is the rate of pay?”
enter rate
wage = hours * rate
display “The wage = R”, wage
end
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.
The preparation is now done, so it’s possible to write a detailed algorithm that
contains every step to solve the problem.
Algorithm
ShowDetails
~ This program will enter the name and the age of the learner and display it on the screen
display “Provide the name of the learner” ~ Display on new line
enter name
display “Provide the age of the learner” ~ Display on new line
enter age
~ Show the details on the screen with appropriate legends
display “The name of the learner is ”, name ~ Display on new line
display “The age of the learner is ”, age ~ Display on new line
end
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:
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.
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
Note that the IPO chart does not contain detailed processing steps.
Algorithm
ConvertDistance
~ Convert km to metres and centimetres
display “Please provide the distance in km. ” ~ Display on new line
enter kilometre
~ Do the conversions
metre = kilometre * 1000
centimetre = metre * 100
~ Display the output on one line
display kilometre, “ km is equivalent to ” , metre, “m and to ”, centimetre, “cm”
end
Output:
If the last display statement is replaced by the following three display statements,
the output will change as follows:
New output:
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
Algorithm
CalcTennisCourt
~ Calculate perimeter and area of tennis court
display “Please enter length” ~ Display on new line
enter length
display “Please enter width” ~ Display on new line
enter width
~ Do calculations and display
perim = 2 * (length + width)
area = length * width
display “The perimeter of the tennis court is ” , perim , “ metres”
display “The area of the tennis court is ” , area , “ square metres”
end
Trace table
The input data to test this algorithm is length = 30 and width = 10.
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:
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
Algorithm
CalculateAverage
~ Prompt for and enter two integers
display “Enter first number” ~ Display on new line
enter num1
display “Enter second number” ~ Display on new line
enter num2
~ Calculate average
average = (num1 + num2) / 2
~ Show average on the screen
display “The average of the two numbers is ” , average ~ Display on new line
end
If the two numbers used as input data were 24 and 40, the output would be:
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
Algorithm
CalcWeeklyWage
~ Calculate and display the weekly wage for Jason
display “Provide number of hours Jason worked” ~ Display on new line
enter hours
display “Provide rate of pay” ~ Display on new line
enter rate
~ Do calculations and display
wage = hours * rate – 8
display “Jason earned R ”, wage, “ for the week.” ~ Display on new line
end
The input data used to test this algorithm: hours worked = 24 and rate of pay
= R12.
Output:
Note that the rate can also be a real value, which would result in a real answer.
Example 6
Problem 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
Note that an intermediate variable can be used to assist with the calculations.
It is not part of the input or the output.
Algorithm
CalculateMoney
display “Provide Tebogo’s monthly salary: ” ~ Enter input
enter salary
remainder = salary – 450 ~ Do calculations
food = remainder * 0.5
clothes = remainder * 0.2
transport = remainder * 0.15
charity = remainder * 0.05
pocket = remainder – (food + clothes + transport + charity)
~ Display results
display “Tebogo divided her salary as follows: ” ~ Display on new line
display “Room R450.00” ~ Display on new line
display “Food R”, food ~ Display on new line
display “Clothes R”, clothes ~ Display on new line
display “Transport R”, transport ~ Display on new line
display “Charity R”, charity ~ Display on new line
display “Pocket money R”, pocket ~ Display on new line
end
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:
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
Algorithm
BuyBulkItems
display “Enter the price of one item to buy”
enter amtOne
amt50_One = amtOne * 0.9
amt100_One = amtOne * 0.875
save1 = amtOne – amt50_One
save2 = amtOne – amt100_One
amt50 = amt50_One * 50
amt100 = amt100_One * 100
save50 = save1 * 50
save100 = save2 * 100
display “A pack of 50 will cost R”, amt50
display “It is a saving of R”, save1, “ per item”
display “and a total saving of R”, save50
display “A pack of 100 will only cost R”, amt100
display “This is a massive saving of R”, save2, “ per item”
display “and a total saving of R”, save100
end
Instruction amtOne amt50 amt100 save1 save2 amt50 amt100 save50 save100 output
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
Algorithm
FoodAlgorithm
~ Input
display “Enter the weight of plate and food in kg”
enter weightFoodPlate
~ Processing
weightFoodKG = weightFoodPlateKG – 1.05
weightFood100G = weightFoodKG * 10
amtDue = weightFood100G * 7.35
amtDue = amtDue + amtDue * 0.14
~ Output
display “Your food weighed ”, weightFoodKG, “kg and it will cost R”, amtDue,
“, 14% VAT included”
end
Example 9
FirstExample
A=3
B=7
A=B–A+2
C=A^2+B–5*2
display “The value of C is ”, C
end
Draw a table that contains only the variables used in the calculations:
A B C
A B C
3
A B C
3
7
A=B–A+2
Substitute the current values of A and B:
A=7–3+2
=6
A gets a new value of 6 to replace the previous value of 3.
A B C
3
7
6
C= A^2+B–5*2
Substitute the current values of A and B:
C= 6^2+7–5*2
= 33
A B C
3
7
6
33
Strike through the 3 in the last 2 tables in order for them to see that A now has
a new value.
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
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
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.
Statements
tax = salary * taxPerc / 100
display “You must pay ”, taxPerc, “% tax on your income”
display “Your tax deduction is R”, tax
netSal = salary – tax
display “Your gross salary is R”, salary
display “Your net salary is R”, netSal
Question 3
Study the following statements. Display the exact output that will be displayed
after these statements have been executed.
3.1
FirstCalculation
A=2
B = 13
C=A*3
B=B–A^2
display “A = ”, A ~ On new line
display “B = ”, B ~ On new line
display “C = ”, C ~ On new line
end
3.2
SecondCalculation
X=4
Y=X+4
Z = Y – 10 * (-X + 7) / 6
display “The sum of X, Y and Z is ”, X + Y + Z
end
3.3
ThirdCalculation
A=5
B=7
C=A*2–1
B=B+2
display “The value of B = ”, B ~ On new line
display “The value of C = ”, C ~ On new line
end
3.4
FourthCalculation
X = 15
Y = 23
Z=2
Y=X*Z\7
W = X mod 8
display “The value of Y is ”, Y ~ On new line
display “The value of W is ”, W ~ On new line
end
3.5
FifthCalculation
k = 12
m = 30
x = (k – 8) ^ 3 + m * 4 / (k – 6)
m=m+2
k = k – 20
display “x = ”, x ~ On a new line
display “m = ”, m ~ On a new line
display “k = ”, k ~ On a new line
end
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
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.
Pseudocode
Description Example Result Precedence
symbol
NOT True False
NOT Yields the opposite 1
NOT False True
True AND True True
Both expressions
True AND False False
AND must be True to 2
False AND True False
yield True
False AND False False
True OR True True
Only one expression
True OR False True
OR must be True to 3
False OR True True
yield True
False OR False 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
Substitute:
X = True OR False AND True
Use parentheses:
X = (A OR B) AND C
= (True OR False) AND True
= True AND True
= True
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
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)
Pseudocode
~ Test if the employee worked overtime
if hours > 45 then
wage = wage + 300 ~ Executed only if the condition is true
endif
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
if condition then
statement(s)
endif
Example
if mark >= 50 then
display “Student has passed”
endif
No Yes No Yes
Condition? Mark > 50?
Student has
Statement(s)
passed
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.
Example:
if NOT condition then if mark NOT < 50 then
statement 1 display “Student has passed”
statement 2 endif
statement 3
statement n
endif
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.
Algorithm
CalcCakePrice
~ Calculate the selling price of cake
display “Provide the cost of the cake” ~ Display on new line
enter expense
~ Add profit and calculate price per slice
cakePrice = expense + expense * 0.3 ~ Intermediate variable cakePrice
slicePriceInteger = cakePrice \ 10
slicePriceDecimal = cakePrice / 10
if slicePriceInteger <> slicePriceDecimal then ~ Test if any cents
slicePriceInteger = slicePriceInteger + 1
endif
~ Display the price of a slice of cake
display “The price of a slice of cake is R” , slicePriceInteger ~ Display on new line
end
Because there is a remainder, 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.
outcome
Instruction expense cakePrice slicePriceInteger slicePriceDecimal output
of if
Provide
the cost
display
of the
cake
enter 18.60
calculate 24.18
calculate 2
calculate 2.418
if True
calculate 3
The price
of a slice
display
of cake
is R3
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:
Example 1
Problem
John wishes to buy a number of pencils at a given price. The seller must enter
values for these variables. If John buys 25 pencils or more, he’ll receive a
discount of 7.5%. Calculate and display the amount due by John.
Planning
Algorithm
CalcAmount
~ Calculate the amount due for pencils
~ Input
display “Provide the number of pencils bought” ~ Display on new line
enter number
display “Provide price of one pencil” ~ Display on new line
enter price
~ Processing
amount = number * price
~ Test if John buys 25 or more pencils
if number >= 25 then
amount = amount – (amount * 0.075)
~ The calculation could also have been amount = amount * 0.925
endif
~ Output
display “The amount due is R ”, amount ~ Display on new line
end
Output:
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
Algorithm
PrepareResult
~ Prepare and display student result
display “Provide mark obtained ” ~ Display on new line
enter mark
~ Initialise message
message = “pass”
~ Test result
if mark < 50 then
~ Could also have been tested using mark <= 49
message = “fail”
endif
~ Display result
display “The mark is ” , mark, “. Result = ”, message ~ Display on new line
end
Output:
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.
Yes No
dept = “A”?
salary = salary +
increase
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
Algorithm
DetermineWinner
~ Determine the winner of the competition
display “Provide points for Angelina” ~ Display on new line
enter pointA
display “Provide points for Freedom” ~ Display on new line
enter pointF
~ Find the winner
if pointA > pointF then
pointW = pointA
winner = “Angelina” ~ More than one statement in body of if
else
pointW = pointF
winner = “Freedom”
endif
~ Display result
display “The winner is ” , winner ~ Display on new line
display “ and the winning points are: ” , pointW
end
Output:
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
Algorithm
ReadingSpeed
display “Provide number of pages per book ” ~ Display on new line
enter bookPages
display “Provide number of pages Dennis can read per day ” ~ Display on new line
enter dayPages
~ Calculate days per book
bookDays = bookPages / dayPages
~ Determine days to read 5 books
days = bookDays * 5 ~ An intermediate
~ variable is used
display “Dennis takes ”, bookDays, “ days per book ” ~ On a new line
~ Test if five books can be read during holidays and display output
if days <= 14 then
message = “Dennis can read five books during the holidays.”
else
message = “It is not possible for Dennis to read five books during the holidays.”
endif
display message ~ Display on new line
end
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.
C = A * B + 3 mod 7
if A > C then
display “A has a higher value than C” ~ Display on a new line
B=A–C
else
display “A is equal to or less than C” ~ Display on a new line
B=C–A
endif
display “The value of B is now ”, B ~ Display on a new line
display “The value of C is now ”, C ~ Display on a new line
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.
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.
No Yes
Grade = “C”?
Bonus = 1000
No Yes
Years > 5?
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.
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
Algorithm
DetermineEntranceFee
~ Enter input data
display “Enter the normal fee ” ~ Display on new line
enter fee
display “Enter the age in years only ” ~ Display on new line
enter age
~ Test age
if age < 12 OR age > 59 then
actFee = fee - fee * 0.25 ~ Subtract discount
else
actFee = fee
endif
~ Display actual fee on a new line
display “This person must pay an entrance fee of R ”, actFee
end
Output:
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
Algorithm
DetermineEntranceFee
display “Enter student name: ” ~ Display on new line
enter stName
display “Indicate if the student is a member or not: ” ~ Display on new line
enter member
~ Test membership
if member then ~ Equivalent to if member = TRUE
message = “ you must pay R8 entrance fee.”
else
message = “ you must pay R12 entrance fee.”
endif
~ Display results
display stName, message ~ Display on new line
end
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:
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.
display “Please provide the hours worked and the tariff per hour ”
enter hours
enter tariff
if hours is numeric AND tariff is numeric then
wage = tariff * hours
else
display “Invalid input values”
endif
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.
x=4
y=x+2
display “Here is the output”
x = x * 2 – y /3
y=x*2
if x >= 8 then
display “The value of x = ”, x ~ Display on a new line
else
x=y-3
display “The value of x = ”, x ~ Display on a new line
endif
w = x + y * 0.5
display x, “ ”, y, “ ”, w ~ Display on a new line
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:
if condition1 then
statement1 ~ Process when condition is true
else
statement2 ~ Process when condition is false
endif
if condition1 then
if condition2 then ⎫
statement1 ⎪
else ⎬ ~ If condition1 is true
statement2 ⎪
endif ⎭
else
if condition3 then ⎫
statement3 ⎪
else ⎬ ~ If condition1 is false
statement4 ⎪
endif ⎭
endif
False True
Condition 1?
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.
The gender of a person is indicated by the code M (male) or F (female).
The age of this male must be less than or equal to 15 because the second if
statement that follows the first else clause is false. There is no need to test for
this condition again. The same rule (logic) applies to the second part of the if
statement where the age for a female is tested.
“Invalid
Points = 20 Points = 17
gender”
False True
Age < 18?
Points = 21 Points = 18
Example 2
Table 1 contains the values of the real variables A and B and the steps to take
when different conditions apply.
Note
To initialise a value means assigning a zero to numeric values and spaces to
non-numeric values.
if A = 5.2 then
if B > 20 then
A=A+5
else
B = B – 3.5 ~ The value of A is still 5.2
endif
else
if A = 6 then
A=0
B=0
endif
endif
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.
Instruction A B Outcome of if
Assign 5.2 25
If A = 5.2 True
If B > 20 True
Calculate 10.2
Table 2: Test 1
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.
Instruction A B Outcome of if
Assign 5.2 15
If A = 5.2 True
If B > 20 False
Calculate 11.5
Table 3: Test 2
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.
Instruction A B Outcome of if
Assign 6 100
If A = 5.2 False
If A > 6 True
Assign 0
Assign 0
Table 4: Test 3
Finally, let’s test the algorithm with A = 8.3 and B = 21 as test data.
Instruction A B Outcome of if
Assign 8.3 21
If A = 5.2 False
If A > 6 False
Table 5: Test 4
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.
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.
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.
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
Algorithm
CalcNewMonSalary
~ Calculate the increased monthly salary
~ Enter input
display “Provide the department code: ” ~ Display on new line
enter deptCode
display “Provide annual salary: ” ~ Display on new line
enter anSalary
if anSalary is numeric then
~ Convert to monthly salary
monSalary = anSalary / 12
~ Calculate increase according to department code
if deptCode = “A” then
monSalary = monSalary + monSalary * 7.2 / 100
else
if deptCode = “B” then
monSalary = monSalary + monSalary * 6.8 / 100
else
monSalary = monSalary + monSalary * 6.3 / 100
endif
endif
~ Display results
display “The increased monthly salary is R ”, monSalary ~ Display on new line
else
display “The annual salary must be numeric.” ~ Display on new line
endif
end
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:
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:
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
Algorithm
CalcMedicine
~ The algorithm will test whether a name has been entered for the dog and whether the
~ weight entered for the dog is numeric and is in kg, to the nearest 500 g, such as 3.5, 5, 6.5. A
~ weight of 7.8 will be invalid. The dosage will be calculated and displayed only if the input is
~ valid.
~ Enter name of dog
display “Provide the name of the dog: ”
enter name
~ Test if name has been entered
if name = “ “ then ~ Outer If statement
display “The name of the dog must be entered.”
else
~ Enter weight only if name has been entered
display “Provide the weight of dog in kg (to nearest 500 g): ”
enter dogWeight
~ Test if weight is numeric, in which case convert it to the equivalent number in 500 g
if dogWeight numeric then ~ Inner If statement 1
number500 = dogWeight * 2
~ Test if weight entered is to the nearest 500 g. If the weight is 3.5, the weight in
~ 500 g will be 7. If the weight is 3, the weight in 500 g will be 6. Therefore the
~ weight in 500 g will never contain a remainder.
if number500 MOD 1 = 0 then ~ Inner if statement 2
if dogWeight < 5 then
medicine = number500 * 1
else
if dogWeight <= 8 then ~ See comment 1
medicine = number500 * 0.9
else
if dogWeight <= 12 then ~ See comment 2
medicine = number500 * 0.75
else
medicine = number500 * 0.6
endif
endif
endif
display name, “must receive a daily dose of ”, medicine, “ml”
else ~ Else clause for inner if statement 2
display “The weight must be in kg and to nearest 500g, e.g. 3, 3.5, or 4”
endif
else ~ Else clause for inner statement 1
display “The weight entered for ”, name, “ must be numeric .”
endif
endif
end
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.
Output:
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.
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
Algorithm
CalcAmtDue
~ Calculate the amount to hire a car
~ Input
display “Enter the type of car you need (S, M or L): ” ~ Display on new line
enter code
display “Enter number of days for car hire: ” ~ Display on new line
enter noDays
~ Validate and calculate amount
if noDays not numeric then
display “Number of days entered not numeric.” ~ Display on new line
display “You entered ”, noDays
else
if code = “S” or code = “s” then
amtDue = noDays * 200
discount = amtDue * 0.125
amtDue = amtDue – discount
display “The amount due is R”, amtDue ~ Display on new line
else
if code = “M” or code = “m” then
amtDue = noDays * 260
display “The amount due is R”, amtDue ~ Display on new line
else
if code = “L” or code = “l” then
amtDue = noDays * 400
display “The amount due is R”, amtDue ~ Display on new line
else
display “Wrong code entered, only S, M or L is valid.”
~ Display on new line
display “You entered the code “, code
endif
endif
endif
endif
end
Output:
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.
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 her 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.
PredictTheAnswer
if code > 8 then
amount = amount * 0.9
else
if code > 5 then
amount = amount * 0.8
else
if code > 3 then
amount = amount * 0.75
else
amount = 0
endif
endif
endif
display “Amount = ” , amount
end
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.
if x < 0 then
if y < x then
z=x+y
else
z=x–y
endif
else
if x < y
z=x*y
else
z=x/y
endif
endif
x y z
5 8
-5 -6
-3 -3
10 5
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
1 kg 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.
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
if number = 1 then
display “Group 1”
else
if number = 3 then
display “Group 3”
else
display “Group unknown”
endif
endif
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.
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!
Planning
Algorithm
RewardingMinutes
~ Initialising a Boolean variable to assume that input entered is valid
validPages = True
~ Input
display “Enter the number of pages read: ” ~ Display on new line
enter pages
if pages is numeric then ~ Validate input
select case pages
case 0 to 20
minutes = 0
case 21 to 50
minutes = 10
case 51 to 100
minutes = 40
case 101 to 400
minutes = 75
case else
display “The pages must be > 0 and not more than 400.”
validPages = False
endselect
else
validPages = False
endif
~ Display output only if input was valid. Display a different message if Summer is not
~ allowed to watch TV.
if validPages = True then
if minutes = 0 then
display “You must read more than 20 pages to watch TV. Better luck next time.”
else
display “Good girl! You may watch TV for ”, minutes, “minutes.”
endif
endif
end
Output:
Exercises
1. Write only the select case statements for the following problem
statements.
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.
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 50 Decrease by 12.5%
None of the above Increase by 10% of A
and calculate and display the amount owed to him. Use a select case
statement to calculate the amount.
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.
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.
if dept = 1 then
salary = salary * 1.1
if salary > 10000 then
bonus = 250
salary = salary + bonus
else
bonus = 500
salary = salary + bonus
endif
else
salary = salary * 1.1
if salary > 20000 then
bonus = 550
salary = salary + bonus
else
bonus = 650
salary = salary + bonus
endif
endif
5.1
a=5
b=7
c = 14
if (a + b) >= (c + 3) then
display “The answer is *” ~ Display on new line
else
if (c – a) <= (b + 2) then
display “The answer is %” ~ Display on new line
else
display “The answer is #” ~ Display on new line
endif
endif
5.2
x = 30
y=7
z = 12
if x = y + 23 AND z = x – y then
k = x + z mod 7
else
if z – x < y - z OR z = x + y then
k = y * (2 + z) \ 3
else
k=x+y+z*2
endif
endif
display “The result is ”, k
5.3
code = 4
digit1 = 5
digit2 = 8
sum = 12
if code > 5 then
sum = sum + digit1 mod 2
display “The sum is increased”
else
if code > 3 then
sum = sum + digit2 mod 11
display “The sum is calculated”
else
display “The sum is not increased”
endif
endif
display “The answer is ”, sum
5.4
money = 20.00
percentage = 5
installment = (money + money * percentage / 100) / 10
display “The amount to be paid is R”, installment
if installment < 2 then
display “The amount is less than R2”
else
if installment < 6 then
display “The amount is less than R6”
else
display “The amount is equal to or more than R6”
endif
endif
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.
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.
k=1
for i = 1 to 10
display k, “ “ ~ On the same line
k=k+1
next i
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:
for i = 1 to 10
display i, “ “ ~ On the same line
next i
i=1
Yes
i > 10?
No
i, ” ”
i=i+1
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:
for i = 10 to 1 step -1
display i, “ “ ~ On the same line
next i
i = 10
Yes
i < 1?
No
i, ” ”
i=i−1
Questions
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.
Note that in this example, the answer is only displayed once, after the loop has
terminated.
sum = 0
odd = 1
k=1
Yes
K > 5?
No
odd = odd + 2
k=k+1
“The sum of
the first 5 odd
numbers is”, sum
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
MultiplesOf5
sum = 0
multiple = 5
display “The first 6 multiples of 5 and their sum: ”
for x = 1 to 6
display multiple ~ On a new line
sum = sum + multiple
multiple = multiple + 5
next x
display “Sum =”, sum
end
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
AverageOf8Integers
sum = 0 ~ Initialise the value of sum to add
~ the integers
for x = 1 to 8
display “Enter any integer between 5 and 48: ” ~ On new line
enter number
if number > 5 and number < 48 then
sum = sum + number
else
display “The number must be between 5 and 48, please re-enter”
x=x–1
endif
next x
average = sum / 8
display “The average of the 8 numbers is ”, average
end
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
Algorithm
DisplayEvenNumbers
~ Calculate the desired even numbers
display “ Provide the beginning even number” ~ Display on new line
enter beginNo
display “How many even numbers must be displayed? “ ~ Display on new line
enter howMany
if beginNo is numeric then
if howMany is numeric and howMany > 0 then
remainder = beginNo MOD 2 ~ Test if beginNo is an even
~ number
if remainder = 0 then
even = beginNo ~ Use a loop to display the even
~ numbers
for x = 1 to howMany
display even, “ “ ~ On one line
even = even + 2
next x
else
display “The begin number must be an even number”
endif
else
display “The number must be numeric and greater than 0”
endif
else
display “The begin number must be numeric”
endif
end
Test the logic with the following four sets of test data:
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.
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.
Algorithm
TestResults
~ Find highest and lowest marks in test results
~ Enter the name and percentage for the first student
display “Enter the name of the first student” ~ Display on new line
enter stName
display “Enter test percentage of the first student” ~ Display on new line
enter testMark
~ Assign values to the names associated with the highest and lowest test scores as these
~ names must also be stored
highestName = stName
highest = testMark
lowestName = stName
lowest = testMark
~ Execute a loop. Repeat 9 times (from student 2 to student 10)
~ For each student, compare his or her marks to the current highest
~ and current lowest mark.
for st = 2 to 10
~ Enter every student name and mark.
~ Indicate number of student in message
display “Enter the name of student no ”, st ~ Display on new line
enter stName
display “Enter test percentage of student no ”, st ~ Display on new line
enter testMark
~ Compare to highest and lowest mark. If necessary, place new
~ name and mark in variables that keep track of highest and lowest scores
if testMark > highest then
highest = testMark ~ Assign higher value to highest
highestName = stName ~ Remember to store name
else
if testMark < lowest then
lowest = testMark ~ Assign lower value to lowest
lowestName = stName ~ Store name as well
endif
endif
next st
~ The results can only be displayed after all the names and their test
~ marks have been entered and compared. The final answers are only
~ ready to be displayed now. Display on a clear screen.
display “The name of the student who obtained the highest mark is ”, highestName
~ Display on new line
display “The highest mark obtained is ”, highest ~ Display on new line
display “The name of the student who obtained the lowest mark is ”, lowestName
~ Display on new line
display “The lowest mark obtained is ”, lowest ~ Display on new line
end
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
Algorithm
DivisionProgram
~ Divide by using subtraction
~ Initialise the result
result = 0
display “Enter the total number to be divided by 5” ~ Display on new line
enter totNumber
if totNumber is Numeric then
if totNumber > 400 then
~ Repeat subtracting until totNumber < 5
for y = totNumber to 0 step –5
~ 5 is subtracted in the step of the Do-until loop control statement
result = result + 1
if totNumber < 5 then
y=0 ~ Too small for another subtraction
endif
next y
display “The number can be divided by five ”, result, “ times”
else
display “The number must be greater than 400”
endif
else
display “The number entered must be an integer”
endif
end
Test the logic using 543 and then 3, followed by x as the total number.
Output:
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.
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.
Choice 1: 5
10
15
20
25
Sum = 75
Choice 2: 1
2
3
4
5
Choice 3: Factorial of 5 = 120
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
10.1
CalculateValue
x=4
y=7
answer = 0
for w = 0 to 4
answer = x + y
x=x+1
y=y–2
next w
display “The value of answer is ”, answer
end
10.2
WillThisOneProvideAnAnswer
a=5
b = 25
for k = 5 to 3 step 2
a=a+b*2
next k
display “The value of a is ”, a
end
Example 9
for i = 1 to 2 ~ Outer loop
for j = 1 to 3 ~ Inner loop statement(s)
next j ~ End of inner loop
next i ~ End of outer 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
Algorithm
CalcResults
~ Produce results of students
totSum = 0
for x = 1 to 4 ~ Loop for 4 students
sum = 0
for y = 1 to 3 ~ Loop for 3 tests
display “Provide test mark ”, y, “ for student ”, x
enter tstMark
sum = sum + tstMark
next y ~ End of test loop
~ Calculate final mark for student
finMark = sum / 3
display “The final mark for student ”, x, “ is ”, finMark
totSum = totSum + finMark ~ Add to total sum
next x ~ End of student loop
~ Calculate and display average
average = totSum / 4
display “The average for all the students is ”, average
end
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. Do the planning and then code an algorithm to solve this problem.
Use 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
CalcOutput
a=0
b = 20
for w = 1 to 5 step 2
for y = 1 to w
answer = a + b – y
a=a+2
b=b–4
next y
display “a = ”, a, “ b = ”, b ~ Display on a new line
next w
display “The answer is: ”, answer ~ Display on a new line
end
2.2
CalculateWithNestedLoop
for x = 4 to 0 step – 2
for y = x to 7 step 2
result = x – y
next y
display “The value of x is ”, x ~ Display on a new line
next x
display “The value of result is ”, result ~ Display on a new line
end
2.3
ShowResults
for x = 1 to 5 step 2
display “x = ”, x ~ Display on a new line
for w = x to 1 step -1
z=x+w
if w > 2 then
display w ~ Display on a new line
endif
next w
display “z = ”, z ~ Display on a new line
next x
display “*****” ~ Display on a new line
end
2.4
TryMe
d=2
x=1
for k = 6 to 1 step -2
for m = k to 8 step 3
s=m+k-d
d=s\2
next m
display “line: ” , x ~ Display on a new line
display “ d = ”, d ~ Display on the same line
x=x+1
next k
end
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.
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:
do
statement 1
statement 2
:
statement n
loop until noTickets = 0 ~ Statement to control the loop
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.
noTickets = 100
do
display “Enter number of tickets to buy”
enter ticketsToBuy
if ticketsToBuy <= noTickets then
noTickets = noTickets – ticketsToBuy
else
display “Sorry, only ”, noTickets, “ ticket(s) still available”
endif
loop until noTickets = 0
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.
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.
CalcSum
~ Accumulate a counter of integers added to a sum
⎫
sum = 0 ~ Initialise sum ⎪ ~ See Comment 1
⎬
number = 24 ⎪
⎭
count = 0 ~ Initialise the counter
do while sum < 23456
sum = sum + number ~ Accumulate the sum
number = number + 1 ~ Proceed to the next consecutive no
count = count + 1 ~ Increment count
loop
display “The number of integers added is ”, count ~ See Comment 2
end
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
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.
FindFishermanWinner
~ Determine who caught the most fish (Example of pre-test do-loop)
winnerNumber = 0 ~ Choose low number
~ for winner
winner = “ ”
display “Provide the number of fish caught by the first fisherman” ~ On a new line
display “Enter -1 to indicate no more input” ~ On a new line
enter noFish
do while noFish <> -1 ~ Test if loop must
~ continue
display “Provide name of fisherman”
enter fmName
if noFish is numeric then
if noFish > winnerNumber then
winnerNumber = noFish
winner = fmName
endif
else
display “The number of fish caught must be numeric”
endif
display “Provide the number of fish caught by the next fisherman” ~ On a new line
display “Enter -1 to indicate no more input” ~ On a new line
enter noFish
loop
display “The name of the winner is ”, winner ~ On a new line
display winner, “ caught ”, winnerNumber, “ fish” ~ On a new line
display “Congratulations ”, winner, “!!!” ~ On a new line
end
Output:
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
Algorithm
AlexisShopping
~ Example of pre-test do loop
total = 0
~ Enter money in her purse once
display “Enter the amount of money in Alexis’ purse”
enter purseMoney
if purseMoney is numeric then
~ If money in purse is valid, enter prices for items to buy in a loop
display “Enter the price of the first item”
enter price
do while price <> 0
if price is numeric then
total = total + price
else
display “The price must be numeric”
endif
display “Enter the price of the next item, enter 0 to stop”
enter price
loop
~ The total amount has now been calculated; determine discount, if any
if total > 100 then
total = total – total * 0.035
~ total = total * 0.965 is equivalent to the statement above
endif
~ Display output
if purseMoney >= total then
change = purseMoney – total
display “Alexis has enough money, she now has R”, change, “ in her purse”
else
shortMoney = total – purseMoney
display “Alexis needs R”, shortMoney, “ more to pay for her purchases”
endif
else
display “The money in her purse must be a numeric amount”
endif
end
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:
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
Algorithm
CalculateNumberTimes
~ Calculate number of times Angel picked strawberries
noTimes = 0
totWeight = 0
do
display “Enter the weight of the strawberries in grams Angel picked” ~ On a new line
enter weight
if weight is numeric then
totWeight = totWeight + weight / 1000
~ Convert to kilograms and add to total weight
noTimes = noTimes + 1 ~ Accumulate count
else
display weight, “ is not a valid input value, please re-enter”
endif
loop until totWeight >= 4.5
~ Number of times has been calculated
display “The number of times Angel picked strawberries is ”, noTimes ~ On a new line
display “She picked a total of ”, totWeight, “ kg of strawberries” ~ On a new line
end
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:
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.
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, …
2. Determine the output of the following algorithms.
2.1
ShowResults2-1
result = 0
count = 0
number = 20
do
result = result + number
count = count + 1
number = number – 4
loop until number < 3
display “result = ”, result, “ count = ”, count
end
2.2
ShowResults2-2
a=5
b=7
answer = 15
do while answer <= 47
answer = answer + a – b
a=a+6
b=b–1
loop
display “answer: ”, answer
end
2.3
ShowResults2-3
for x = 1 to 5 step 2
display “x = ”, x ~ Display on a new line
w = 0
do while w < 10
w = w + x * 3
z = x + w
if w > 12 then
display w ~ Display on a new line
endif
loop
display “z = ”, z ~ Display on a new line
next x
display “*****” ~ Display on a new line
end
2.4
ShowResults2-4
w=1
do while w <> 4
k=4
w=w+1
for b = 1 to 2 step 0.5
k = k * 2 + b - w
next b
display k ~ Display on a new line
loop
display “k = ”, k, “ w = ”, w ~ Display on a new line
end
2.5
ShowResults2-5
x=5
y=7
display “Begin” ~ Display on a new line
for a = 1 to 12 step 5
display “a = ”, a ~ Display on a new line
do
z=a*x+y
y=y–1
x=x+1
loop until y < 7
display “y = ”, y ~ Display on a new line
next a
display “x = ”, x ~ Display on a new line
display “a = ”, a ~ Display on a new line
display “z = ”, z ~ Display on a new line
display “End” ~ Display on a new line
end
3. Study the following algorithms, then predict how many times the
message “this is output” will be displayed on screen.
3.1
ShowOutput
a=0
do while a < 7
display “this is output” ~ Display on a new line
a=a+1
loop
end
3.2
AnotherOutputProgram
x=2
y=3
do
x=x+1
do while y <= 5
display “this is output” ~ Display on a new line
y=y+2
loop
display “this is output” ~ Display on a new line
loop until x = 6
display “this is output” ~ Display on a new line
end
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:
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:
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:
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:
• monthArray – 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
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.
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.
CalculateFinalMark
display “Please provide the percentage for test 1”
enter T1
display “Please provide the percentage for test 2”
enter T2
display “Please provide the percentage for test 3”
enter T3
display “Please provide the percentage for test 4”
enter T4
display “Please provide the percentage for test 5”
enter T5
display “Please provide the percentage for test 6”
enter T6
display “Please provide the percentage for test 7”
enter T7
display “Please provide the percentage for test 8”
enter T8
display “Please provide the percentage for test 9”
enter T9
display “Please provide the percentage for test 10”
enter T10
finalMark = (T1 + T2 + T3 + T4 + T5 + T6 + T7 + T8 + T9 + T10) / 10
display “The final mark for the student = ”, finalMark, “ %”
end
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.
CalculateFinalMark
totalMark = 0
for T = 1 to 10
display “Please provide the percentage for test ”, T
enter testMark
totalMark = totalMark + testMark
next T
finalMark = totalMark / 10
display “The final mark for the student = ”, finalMark, “ %”
end
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.
for T = 0 to 9
display “Please provide the percentage for test ”, T + 1
enter testMark(T)
totalMark = totalMark + testMark(T)
next T
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
Variable/array
Description Type
name
10 test marks
Input entered in an Integer testMark
array
Total of these
Intermediate Integer totalMark
marks
10 test marks
Output entered in an Integer testMark
array
Final mark Real finalMark
Algorithm
CalculateFinalMark
totalMark = 0
for T = 0 to 9
display “Please provide the percentage for test ”, T + 1 ~ Display on a new line
enter testMark(T)
totalMark = totalMark + testMark(T)
next T
finalMark = totalMark / 10
for T = 0 to 9
display “Test ”, T+ 1, “ = ”, testMark(T), “%” ~ Display on a new line
next T
display “The final mark for the student = ”, finalMark, “%” ~ Display on a new line
end
After the algorithm has been executed, the variables can be represented as
follows:
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
CalculateFinalMark
totalMark = 0
for T = 0 to 9
display “Please provide the percentage for test ”, T+ 1 ~ Display on a new line
enter testMark(T)
totalMark = totalMark + testMark(T)
next T
lowestMark = testMark(0)
for T = 1 to 9 ~ Start with second element
if testMark(T) < lowestMark
lowestMark = testMark(T)
endif
next T
totalMark = totalMark – lowestMark
finalMark = totalMark / 9
for T = 0 to 9
display “Test ”, T+ 1, “ = ”, testMark(T), “%” ~ Display on a new line
next T
display “The final mark for the student = ”, finalMark, “%” ~ Display on a new line
end
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
FindEmployee
boolFound = False
display “Enter the identity number of the employee”
enter idNo
for m = 0 to 7
if empIds(m) = idNo then ~ empIds is an array with 8 elements
boolFound = True ~ The person is found!
m=7 ~ Exit the loop
endif
next m
if boolFound = True then
display “The person whose id number is ”, idNo, “ is an employee”
else
display “The person whose id number is ”, idNo, “ is not an employee”
endif
end
Example 4
An array called evenNumbers, which has 44 elements with consecutive even
numbers starting at 14, needs to be filled.
Algorithm
FillArray
~ This algorithm fills the array with consecutive even numbers starting at 14.
~ Use an array evenNumbers with 44 elements of the type integer
number = 14
for i = 0 to 43
evenNumbers(i) = number
number = number + 2
next i
end
Algorithm
FillArray
display “Enter the first even number with which to fill the array”
enter firstNumber
if firstNumber is numeric then
if firstNumber Mod 2 = 0 then ~ Test if it is an even number
number = firstNumber
for i = 0 to 43
evenNumbers(i) = number
number = number + 2
next i
else
display “The number must be an even number”
endif
else
display “You did not enter a numeric value”
endif
end
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
FindHighest
~ Assume the array already contains the valid values
~ Compare all the values in the array to find and display the highest value
foundAtIndex = 0
highest = noInStock(0) ~Assign first value to highest
for k = 1 to 19
if noInStock(k) > highest then
highest = noInStock(k)
foundAtIndex = k
endif
next k
~ After testing the values in all the elements, the highest can now be displayed.
display “The highest value in the array noInStock is: ”, highest
display “It was found at index position “, foundAtIndex
end
Output:
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:
number
1
2
3
4
5
6
7
8
Process the code given below and display the new values for the array in
the space provided:
for i = 1 to 6 step 2 number
number(i) = number(i+1)
number(i - 1) = i + number(i)
next i
T O D A Y I S A L O V E L Y S U N N Y D A Y
8. Determine the value of the array called abc after the following statements
have been processed:
abc
2
3
4
5
6
7
8
9
10
y = abc (0)
for x = 1 to 6 step 2
abc (x) = abc (y - 1) + 2
next x
z = abc (7)
for y = abc (2) to 8
abc (y) = z + y
next y
array_s
4
7
2
3
8
5
1
9
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.
XYZ
4
17
23
54
43
23
1
77
82
10
11.1 What will the value of answer be after the following statements
have been executed?
x=8
answer = XYZ(3) + XYZ(x) + x
number
1
2
3
4
5
6
7
8
Process the code given below and show the new values in the array:
for i = 0 to 5 step 2 number
number(i) = number(i+1)
number(i+3) = i + number(i)
next i
13. The array called priceVal can contain 10 integer value elements. Process
the code given below and show the new values in the array.
for i = 0 to 9 priceVal
priceVal(i) = i * 2
next i
m=4
do while priceVal(m) > 5
priceVal(m) = priceVal(m + 1)
m=m-1
loop
for j = m to 9
priceVal(j) = priceVal(j) * 3
next j
14. The array XYZ can contain 10 numeric elements. Process the code given
below and show the new values in the array.
k=4 XYZ
for x = 1 to 9
XYZ(x) = k / 2
k= k + 4
next x
for y = 1 to 9
XYZ(y - 1) = XYZ(y)
next y
w=0
for z = 0 to 7 step 3
XYZ(w) = XYZ(z + 1) + 3
w=w+1
next z
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
FindDescription
~ Find the description for an entered item code.
~ Assume the arrays already contain the valid values
itemIndex = 0
display “Provide the code of an item”
enter itemCode
do while itemIndex < 5 AND code(itemIndex) <> itemCode
itemIndex = itemIndex + 1
loop
~ Display the answer
if itemIndex < 5 then
display “The description for ”, itemCode, “ is ”, description(itemIndex)
else
display “You entered an incorrect item code”
endif
end
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.
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:
3
4
5
3
2
3
6
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:
Algorithm
CalcResults
~ The program will calculate the results of students
for st = 0 to 19 ~ Loop student 20 times
total = 0 ~ Initialise the total for 1 student
for test = 0 to 3 ~ Loop test 4 times
total = total + stMarks(st, test) ~ Add mark of student to his/her total
next test
stFinalMark(st) = total / 4 ~ Calculate and store average st mark
~ in array
next st
for st = 0 to 19 ~ Display details of every student
display “St no: ”, stNum(st), “ St name: ”, stNames(st),
“Final mark: ”, stFinalMark(st)
next st
~ Find the best student
best = stFinalMark(0) ~ Set best to mark of 1st student
student = stNames(0)
for st = 1 to 19
if stFinalMark(st) > best then
best = stFinalMark(st)
student = stNames(st) ~ Store name as well
endif
next st
~ Display the best student
display “The best student is: ”, student, “ and his mark is: ”, best
end
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%.
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.
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.
fillAsteriskArray
for a = 0 to 4
for b = 5 to 6
arrayC(a,b) = “*”
next b
next a
a=4
b=4
for c = 5 to 8
for d = a to b
arrayC(c,d) = “*”
next d
a=a–1
b=b+1
next c
end
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.
20
5
15
36
4
36
20
15
5
4
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.
Algorithm
SortPetNames
~ This program will sort the names of the pets in ascending order. We can assume that
~ the array already contains values.
p = 12
for k = 0 to 13 ~ The array must be sorted 14 times
for m = 0 to p ~ Number of comparisons
if petNames(m) > petNames(m+1) then
temp = petNames(m) ~ Use temp to store the value
petNames(m) = petNames(m+1)
petNames(m+1) = temp
endif
next m
p=p–1
next k
end
Initial order 1st pass 2nd pass 3rd pass 4th pass
14 2 2 2 2
3 3 3 3 3
12 12 12 5 5
2 14 14 14 12
5 5 5 12 14
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.
Algorithm
SortPetNames
~ This program will sort the names of the pets in descending order
~ The array already contains values
for g = 0 to 13
biggest = petNames(g) ~ Set initial values to
position = g ~ find the biggest
for h = (g+1) to 14
if petNames(h) > biggest then
biggest = petNames(h)
position = h
endif
next h
petNames(position) = petNames(g)
petNames(g) = biggest
next g
end
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 mudularisation,
• 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.
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.
StudentMainModule()
CalcPredicate() CalcFinalMark()
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.
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.
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)
A display statement
Use the same example, but don’t store the answer in sum; instead display the
sum of the two numbers.
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.
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)
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.
Calcsum(valNumber1, valNumber2)
total = valNumber2 + valNumber2
return total
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
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.
ShoppingProgram()
CalcAmtDue()
Planning
Algorithm
Function CalcAmtDue (valNum, valPrice)
return (valNum * valPrice * 1.14)
ShoppingProgram
~ The input data will be entered in the main procedure.
~ The main procedure will then call a function to calculate the amount due.
~ The amount due will be displayed in the main procedure.
display “Enter the number of fruit bars bought”
enter numItems
display “Enter the price of a fruit bar”
enter price
amtDue = CalcAmtDue (numItems, price) ~ Function call
display “The amount due is R”, amtDue
end
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.
ShowResults()
CalcAve() DetermineResults()
Planning
Algorithm
Function CalcAve (valTest1, valTest2, valTest3) ~ Function
~ Calculate and return the average of the three tests
return (valTest1 + valTest2 + valTest3) / 3
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
Function Calculation(valX, valY)
return (valX + valY \ 2)
JustACalculation
a = 14
b=5
answer = Calculation(a, b)
display “The answer is ”, answer
end
2.2
Function AddNumbers(valA, valB)
c= valA + valB
return c
MainAlgorithm
a=0
b=1
do while a < 5
x = AddNumbers(a, b)
b=a+5
a=a+1
display “a = ”, a , “ b = ”, b , “ x = ”, x ~ Display on a new line
loop
end
3. The formula to calculate the Body Mass Index for a person is as follows:
Weight
BMI = _______2
Height
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:
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.
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.
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.
Here’s the subprocedure header for the subprocedure call in the previous
paragraph:
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.
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.
EarnInterest()
Planning
Algorithm
Sub DisplayResults (valMonth, valAmt, valMInt) ~ Display monthly values
display valMonth, “ ”, valAmt, “ ” , valMInt
End Sub
EarnInterest
~ This program deals with the investment of money
totInterest = 0
monInt = 0
display Headings
display “Provide the amount you want to invest”
enter amount
display “Enter the monthly interest rate”
enter rate
call DisplayResults (0, amount, monInt) ~ Display initial values
~ Repeat 15 times to obtain final results
for x = 1 to 15
call CalcNewValues (rate, amount, monInt)
call DisplayResults (x, amount, monInt)
call AccSum (monInt, totInterest)
next x
display “The total amount of interest earned is R”, totInterest
end
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:
Assessment Weighting
Test 1 15%
Test 2 20%
The better of two class
15%
test marks
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.
CalFinalMarks()
CalcCTMark() CalcValues()
DisplayResults()
Planning
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 – pass
String message
or fail
Subprocedure (DisplayResults)
Copy of final
Parameters Integer valFinalMark
marks
Copy of result
String valMessage
message
Output Final mark Real valFinalMark
Message String valMessage
Algorithm
Function CalcClMark (valClMark1, valClMark2) ~ Function header
if valClMark1 > valClMark2
betterMark = valClMark1
else
betterMark = valClMark2
endif
return betterMark
CalcFinalMark
Main procedure
display “Provide the mark for test 1”
enter test1
display “Provide the mark for test 2”
enter test2
display “Provide the mark for class test 1”
enter clTest1
display “Provide the mark for class test 2”
enter clTest2
display “Provide the exam mark”
enter exam
betterClassTest = CalcClMark (clTest1, clTest2) ~ Function call
call CalcValues (test1, test2, betterClassTest, Exam) ~ Call subprocedure
end
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 higher 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.
Example 5
A function is called to enter the discount that applies to a product. The discount
may never be more than 25%.
Function CalcPercDiscount()
do
display “Enter the percentage discount that applies”
enter percDiscount
if percDiscount < 0 or percDiscount > 25 then
display “Invalid discount – please re-enter”
endif
loop until percDiscount >= 0 and percDiscount <= 25
return percDiscount
mainModule
display “Enter the price of the product”
enter price
discount = calcPercDiscount()
amtDue = price – price * discount / 100
display “Amount due = R”, amtDue
end
Exercises
1. What will the exact output be after each of these program segments has
been executed?
1.1
Sub IsntItLovely (valA, refB, valC, refD)
refD = valA
if refB mod 3 = 0 then
refB = refB + 2
endif
refD = valA + (valC mod 5)
valA = valA + 2
valC = valC + 1
End Sub
MainAlgorithm
w=0
x=3
y=8
z=6
for m = 4 to 9 step 3
w=m
call IsntItLovely(w,x,y,z)
display “w = ” , w , “ x = ” , x , “ y = ” , y , “z = ”, z
next m
end
1.2
Sub CalcProc (valA, refB)
c = valA * 3
refB = c - refB
End Sub
MainModule
m=4
l=1
k=2
do
j = CalcFunc (m)
call CalcProc (j, k)
display “ l = “ , l , “ j = “ , j , “k = “, k , “m = “, m
m=m+1
loop until m > 5
end
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.
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
4 Life Orientation 6
Drawing
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.
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.
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:
if exists(students.txt) then
open input(students.txt)
else
display “The file does not exist”
endif
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.
if exists(employees.txt) then
open input(employees.txt)
EmployeeData = read(employees.txt)
do until eof
display EmployeeData
EmployeeData = read(employees.txt)
loop
close(employees.txt)
else
display “The file does not exist.”
endif
Note that the first line of text is read before the loop. The first 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.
MainModule()
DisplayHeadings() GetFields()
MainModule
if exists(employees.txt) then
open input (employees.txt)
call DisplayHeadings()
EmployeeData = read(employees.txt)
do until eof
call GetFields(EmployeeData, empNum, empName, empDept, empJob)
display empNum, “ ”, empName, “ ”, empDept, “ ”, empJob
EmployeeData = read(employees.txt)
loop
close (employees.txt)
else
display “The file does not exist.”
endif
end
Because string manipulation is not covered in this book in detail, the code for
the sub procedure is not provided.
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:
do until eof
EmployeeData = read(employees.txt)
Display EmployeeData
loop
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.
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 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.
open outputCreate(employees.txt) ~ Opens the file. If it exists, the current content will
~ be erased.
display “Enter the first line of employee data, enter -1 to stop”
enter EmployeeData
do while EmployeeData <> “-1”
write(employees.txt) from EmployeeData
write new line
display “Enter the next line of employee data, enter -1 to stop”
enter EmployeeData
loop
close(employees.txt)
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:
open outputCreate(employees.txt)
display “Enter the number of the first employee, enter -1 to stop”
enter empNum
do while empNum <> -1
display “Enter the name of this employee”
enter empName
display “Enter the department”
enter empDept
display “Enter his/her job description”
enter empJob
Concatenate empNum, “*”, empName, “*”, empDept, “*”, empJob, “#”
into EmployeeData
write(employee.txt) from EmployeeData
write new line
display “Enter the number of the next employee, enter -1 to stop”
enter empNum
loop
close(employees.txt)
Example 3
Let’s say we need to change either the job description or department of
particular employees.
Initial planning
Step 1: Read the entire file into an array
Step 2: For all employee data that needs to be changed
Accept the employee number
Check if it exists in the array
Ask if job description must be changed
MainModule()
GetFields() UpdateArrayElement()
Note that the code for the GetFields() sub procedure is not provided because
detail string manipulation techniques are not covered in this book.
Algorithm
MainModule
empIndex = 0 ~ Global variable
~ Step 1
call ReadFileIntoArray()
~ Step 2
display “FILE UPDATING: Enter the employee number, -1 to stop the process”
enter empNumber
do while empNumber <> -1
call UpdateRecords()
loop
~ Step 3
call CreateFileFromArray()
End
Sub ReadFileIntoArray()
if exists(employees.txt) then
open input (employees.txt)
EmployeeData = read(employees.txt)
do until eof
call GetFields(EmployeeData)
~ In this sub procedure string manipulation statements will be used to divide
~ the text line into empNum(empIndex), empName(empIndex),
~ empDept(empIndex) and empJub(empIndex) - all part of a global array.
~ The code for this procedure will not be provided
empIndex = empIndex + 1
EmployeeData = read(employees.txt)
loop
~ Subtract 1 from empIndex to indicate the exact length of the array
empIndex = empIndex - 1
close (employees.txt)
else
display “The file does not exist”
endif
End Sub
Sub UpdateRecords()
~ Search for corresponding array position
~ empIndex now contains the length of the array
foundIndex = 0
do while foundIndex < empIndex and empNum(foundindex) <> empNumber
foundIndex = foundIndex + 1
loop
if foundIndex < empIndex then
~ emp number found in array
~ Call a sub procedure to handle the update process
call updateArrayElement(foundIndex)
else
display “Invalid employee number”
endif
display “Enter the next employee number, -1 to stop the process”
enter empNumber
End Sub
Sub UpdateArrayElement(valFIndex)
display “Do you want to change the department for this employee? Y/N”
enter changeDept
display “Do you want to change the job description for this employee? Y/N”
enter changeJob
if changeDept = “Y” or changeDept = “y” then
display “Provide the new department”
enter empDept(valFIndex)
endif
if changeJob = “Y” or changeJob = “y” then
display “Provide the new job description”
enter empJob(valFIndex)
endif
End Sub
Sub CreateFileFromArray()
open outputCreate(employees.txt)
newIndex = 0
do while newIndex < empIndex
~ Concatenate each output line from array elements
Concatenate empNum(newIndex), “*”,
empName(newIndex), “*”,
empDept(newIndex), “*”,
empJob(newIndex), “#”
into EmployeeData
write(employee.txt) from EmployeeData
write new line
loop
close(employees.txt)
End Sub
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.
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.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.
(Data)
Properties
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.
Characteristics Examples
Are abstractions, concepts or things Human being
Human being knows his or her
Have clear boundaries
physical capabilities
Are found in the problem domain References to use for species
Know things about themselves Height, weight
Interact with other humans and
Interact with other objects
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.
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.
Class: Car
Attribute Name Type
Type String
Make String
Model String
Colour String
Table 3: The class called Car, and two instances of the class
You can see that the two instances of the class Car have the same attributes,
but different values.
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:
Interface
Public attributes Message from another object
and operations
Implementation
Private attributes
and operations
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.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.
Uses
Employee Company
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.
car
body wheel
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().
Vehicle
Fuel_consumption
Speed
Power Properties
Engine_Size
Number_of_Wheels
Stop()
Accelerate() Operations
Change gears()
Load()
Unload()
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.
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.
FindTheBigger
display “Enter a number”
enter num1
display “Enter the next number – not equal to the first number”
enter num2
if num1 > num2 then
display “num1 is bigger than num2”
else
display “num2 is bigger than num1”
endif
end
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.
CountTheNumber
sum = 0
count = 0
do while sum <= 200
display “Enter an integer between 5 and 20”
enter num
sum = sum + num
count = count + 1
loop
display “The number of integers is “, count
end
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:
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.
Begin
Ask for
num1
Enter
num1
Ask for
num2
Enter
num2
False True
num1 >
num2?
“num2 is “num1 is
bigger than bigger than
num1” num2”
End
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.
Begin
sum = 0
count = 0
Sum <=
200 False
True
Ask for
num
Enter
num
sum=sum + num
count=count+1
“The number
of integers is”
count
End
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.
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
display “num1 is bigger than num2” display “num2 is bigger than num1”
end
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
sum = 0
count = 0
sum < = 200
display “Enter an integer between 5 and 20”
enter num
sum = sum + num
count = count + 1
display “The number of integers is”, count
end
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 a 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.
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
CalcProduct
~ This program calculates the product of two integers
display “Enter the first integer”
enter num1
display “Enter the second integer”
enter num2
product = num1 * num2
display “The product is “, product
end
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
BuyTickets
display “How many tickets do you want to buy? “
enter noTickets
if noTickets < 10 then
amtDue = noTickets * 30
else
if noTickets < 20 then
amtDue = noTickets * 28
else
amtDue = noTickets * 25
endif
endif
display “The amount due for “, noTickets, “ tickets is R”, amtDue
end
Now we’re going to test this algorithm using 20 as the number of tickets.
Outcome
Instruction noTickets amtDue Output
of If
How many
tickets do
display
you want to
buy?
enter 20
if False
if False
calculate 500
The amount
due for 20
display
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.
BuyTickets
display “How many tickets do you want to buy? “
enter noTickets
if noTickets < 10 then
amtDue = noTickets * 30
else
if noTickets <= 20 then
amtDue = noTickets * 28
else
amtDue = noTickets * 25
endif
endif
display “The amount due for “, noTickets, “ tickets is R”, amtDue
end
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.
In each case, calculate the answers beforehand to ensure that your algorithm
produces the correct answers.
Glossary
Accumulation Character
Accumulation is used in problem solving to A single number, letter or special character;
calculate a total or an average. When you any one stroke that can be typed on a
add 1 to the accumulator during every keyboard.
execution of the loop, the accumulator is Character variable
called a counter. A variable that contains a single letter,
Accumulator number or special character,
A variable that acts as a register to store the Compound If statement
results of an accumulation process. A statement used to test more than one
Aggregation condition before the result can be
In terms of the relationships between object evaluated to be either true or false.
classes, aggregation occurs when one class Class
is part of another class. A construct used as a template to create
Algorithm objects that have predefined properties.
A set of instructions written in a specific Constant
sequence to solve a problem. A fixed value that cannot change throughout
Argument list the entire program; may be any data type.
The list of variables in the call statement that Data
correspond to the list of parameters in the A collection of facts, such as values,
function or subprocedure. measurements, or readings.
Array Database
Variables of the same data type grouped A number of related files or tables.
under a single name. Data errors
Array element Incorrect data that causes a program to cease
A single variable in an array that can contain processing or provide incorrect results.
a value at a given time. Data processing
Association A sequence of operations performed on data
An expression of the relationship between to generate information.
two object classes. Data validation
Boolean variable A test to check that input data can be used by
A variable that can take only one value, true the program in its current format.
or false. Data warehouse
Bubble sort The largest structure used to collect and store
A sorting method in which elements in an data for processing, analysis and reporting;
array are compared to each other in pairs; may consist of several databases.
when an element is not in sequence, it Encapsulation
trades places with the other element until Also known as information hiding, a
all elements are sorted in the required technique that makes the internal workings
sequence. of a class invisible to all other classes.
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.
Index
C E
calculations, algorithm 46–48 element 154
CalcSum 185 encapsulation 222–223
calling a function 187 equals sign meanings 11
calling a function examples 187–190 errors, data 237
calling statement 185 evaluate algorithm 26
call function 184–185 examples, algorithm 29
character 2–3 examples of names, types and values 7
character variable 6
class 222
F K
false value 6 key words in arithmetic expressions 9–10
fields 2, 3 L
file pointer 206 list all steps 25–26
files 2, 3 logical errors, debugging 237
fixed value 8, 14 logical operator 54
flowcharts 29, 145–146, 230–233 logical operator examples 54–57
For-next-loop 110–111 logical variable 6
For-next-loop examples 111–125 loop, nested 128–129
for statements, nested 128–129 loop, nested examples 129–132
function
call 184–185 M
header 185–186 main module 182
name 185–186 methods 221
procedures 181, 184–192 modularisation 182
function, no parameters 199–204 modules 181
multiple inheritance 227
H
header, data 184–185 N
hierarchy chart 182 name, function 185–186
hierarchy data 2–4 naming a variable 4–5
naming variable rules 4
I Nassi-Shneidermann diagrams (NSD) 29,
If statement 52, 57–65, 58, 158 233–235
If statement examples 62–65 nested
If statement testing 59–61 for statements 128–129
If statement, nested 80–86 If statements 80–86
If statement, nested in programs, examples If statements in programs, examples 87–94
87–94 If statement examples 82–86
If statement, nested examples 82–86 loop 128–129
If-then-else statement 52, 66 loop examples 129–132
If-then-else statement examples 67–70 non-numeric variables 6
implementation 223 non-zero value 6
independent subprocedure examples no parameters function 199–204
194–199 no parameters subprocedure 199–204
index 154 numeric variables 5–6
information 23
information hiding 222–223 O
inheritance 226–227 object characteristics 220
initial value 8 object-oriented approach 218
input 23, 205 object-oriented solution design 228
Input/Processing/Output (IPO) chart 32–36, objects 219
37 one-dimensional array 154, 156–157
integer variables 5–6, 15 one-dimensional array examples 157–162,
item, data 3 171
interface 223 OO language 219
Intermediate variables 60 opening sequential access files 206–207
iteration 31, 133–136 operands 11, 13
operations, object 219, 221–222
operator precedence 55, 56
P S
paired arrays 169 same sequential access files 214–217
parallel arrays 169 select case structure 98–99
parallel arrays example 169 select case structure examples 100–103
parameters 183–184 selection 31
parentheses 12–14, 57 selection control structure 52
phases, algorithm 23 selection sort method 179
post-test loop 135 selection sort method example 180
post-test loop flowcharts 146 sentinel 135
pre-test loop 134 sequence 31
pre-test loop flowcharts 144–145 sequential access files 205–207
private attributes 223 closing 207
private scope 220 opening 206–207
problem reading 208–211
analysis 24–25 same 214–217
solving 18–19 writing 212–214
solving steps 18–19 signature 221
statement 19 solving, problem 18–19
statement examples 19–22 solving steps, problem 18–19
problem-solving approach 24–30 sorting arrays 176–180
procedures, function 181, 184–192 statement, problem 19
processing 23 statement examples, problem 19–22
processing, data 23–24 steps, algorithm 33–36, 39
processing examples, data 23–24 string variable 6
program planning 31–36 sub class 227
program planning examples 31–48 sub modules 182
programmers 4 subprocedure call 193
properties, object 219, 220–221 subprocedure header 193–194
pseudocode 26–29, 53, 229–230 subprocedure, no parameters 199–204
pseudocode example 26–28 subprocedures 181, 183, 193–204
public attributes 223 subscript 154
public scope 220 super class 227
syntax errors 236–237
Q
quotes, use of 6 T
tables 2, 3
R terminating execution of a loop 135–136
reading sequential access files 208–211 testing, algorithm 36–45
real number variables 6, 15 text files 205
records 2, 3 trace tables 36, 237–240
reference parameters 183–184 true value 6
referencing 155 two-dimensional arrays 171–172
relational comparisons 53 type, data 154
relational operations 53–54 types and values, examples of names 7
relational operators 53