Basic Programming Principles (2nd Edition)
Basic Programming Principles (2nd Edition)
Principles
Second Edition
CM Pretorius
HG Erasmus
Pearson Holdings Southern Africa (Pty) Ltd.
www.pearsoned.co.za
1 Data hierarchy 2
1.1 Character 2
1.2 Field 3
1.3 Record 3
1.4 File 3
1.5 Table 3
1.6 Database 3
2 Variables 4
2.1 Naming a variable 4
3 Constants 8
1 Problem solving 18
3 Data processing 23
1 Program planning 31
1 Relational operations 53
2 Logical operations 54
5 Compound If statements 71
6 Data validation 77
Chapter 5 The selection control structure: Part 2 80
Introduction 80
1 Nested If statements 81
1.1 Nested If statements in programs 87
3 Parameters 183
3.1 Value parameters 183
1 Pseudocode 229
2 Flowcharts 230
Glossary 241
Bibliography 244
Chapter 1 General
concepts and arithmetic
Introduction
Throughout our lives, we’re confronted
with problems we need to solve – for
instance, fixing a plug at home, taking
action to increase profits at work and
even trying to buy everything we need
within our budget when we go
shopping. Sometimes we solve a
problem without consciously going
through a formal process. We simply
execute a number of steps to come to
the solution.
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.
Database ⇑
Record ⇑
Field ⇑
Character Smallest
1.1 Character
A character can be a single number, letter or special
character. Any one stroke that can be typed on a
keyboard is a character. Examples are 4, A, % and m.
1.2 Field
A field consists of a number of characters, such as a
number of persons (120) or a name (John). A field is
also known as a data item. The data types of fields are
discussed in section 2.2.
1.3 Record
Records normally group related fields together, such as
a student record, which could contain a student number,
the student’s name and surname and the course that
the student has enrolled for. Another example is an item
in a shop – the record could contain the item number,
description and price.
1.4 File
A file is a collection of related records such as an
employees file that contains records of all the
employees employed by a specific company. This file
may be used to process monthly salaries, print salary
reports and produce summaries. The records in the file
are organised and stored in a specific way, for
instance, sequentially one after the other.
1.5 Table
A table is a structure made up of rows and columns.
Each row represents the data of one entity regarding a
specific topic, e.g. data about one item in a shop, and
each column contains a category of data. For instance,
in an Employees table, one employee’s row would
contain the same categories of data, such as surname
and first name, as the other employees’ rows. However,
the data or values in each row would be different.
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.
2 Variables
Programmers use the term ‘variable’ to refer to a
position or location in the memory of the computer
where a value can be stored. Initially, the variable need
not contain a value. The word variable indicates that the
value of the variable may vary as needed, or as
processing is done. You can visualise a variable as a
box in memory that contains one and only one specific
value at a given time.
2.1 Naming a variable
Every variable is given a descriptive name. There is no
need for the programmer to know the exact position
(address) of the variable, because the compiler will link
the given name of the variable to the actual address in
memory. When solving a problem, only one name is
given to a variable and this exact name is used all the
time. Although we are not writing the computer program
as yet and are still busy with the planning, we should
start to adhere to programming rules regarding the
choice of variable names.
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.
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.
Exercises
Complete the following table:
Colour of dress
Height of person in
metres
Adult?
Age in years
Salary in R/c
Title of book
Player in match?
Name of lecturer
Number of computers
3 Constants
All the rules of variables apply to constants as well,
except that constants have a fixed value that cannot
change throughout the entire program. Constants are
used in cases where we know that the value will never
vary during the execution of the program. A constant
may be any data type.
Examples:
There are always 24 hours in a day.
4 Using variables in
expressions and
assignments
The assignment symbol (=) is used to assign an initial
value or an expression to a variable.
or
Variablename = Expression
Example: totalNumStudents = 20
Addition
Key Examples
words
Total of Calculate the total of the first and the second sets of
quantities.
Added to The 4th test mark must be added to the final mark.
Subtraction
Fewer than Goodman has worked five hours fewer than Samuel.
Multiplication
Key Examples
words
Division
Key Examples
words
Ratio If the ratio of girls to boys is 2:3 and there are 25 children,
how many girls are there?
Key Examples
words
Sold for The final amount four items were sold for is R84.
answer = 4 + 7
The calculation to the right of the equal sign is done
first, then the result is assigned to the variable on the
left of the equal sign, which is ‘answer’ in this case. So
after the statement is executed, the variable called
answer will contain a value of 11.
^ Exponentiation 2 ^4 16 1
(to the power of)
\ Integer division 37 \ 5 7 4
X=A^3−2*B+(2*(C+D))/2
Example:
Rewrite the following mathematical equation in
computer-related format as an assignment statement to
obtain the value of A:
3A = 2 (C – D )
A = (2 * (C – D)) / 3
Exercises
Rewrite the following equations in computer-related
format to determine the value of X, where A, B, C, D, E
and X are numeric variables:
4
1. X = AB + C4
2. X=C−DE+5−5D
3. X = 17BC - B(E-A)
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?
Constants hours = 8
(integers):
payRate = 11
transport = 12
noDays = 5
Example 2
Thandi has 257 items and wants to pack them in
packets of 14 each. How many full packets will she
have?
noInPacket = 14
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.
busFare = 3.6
noHours = 8
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
Exercises
Question 1
Complete the following table:
Description Variable Variable Possible
name type value
Number of pencils
Symbol (A, G, R or T)
Employed?
Weight of bean in mg
Price of bread
Gender (M/F)
Notice on door
Number on door
Able to swim?
Question 2
Choose suitable variable names for each of the
following and assign values where provided:
Question 3
Rewrite in computer-related format, then calculate the
value of x in each of the following equations:
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.
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.
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!
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.
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.
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.
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.
Packaging The cost of packaging the item and paying the postage.
and posting Also called shipping costs.
cost
Check the The company will contact the bank online to ensure that
details the credit card details are valid and that there are
sufficient funds in the account to cover the purchase
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.
Total The sum of all the salary increases for all employees
increase
3 Data processing
An algorithm is divided into three phases:
Figure 1
The phases in an algorithm
In other words:
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.
Example 7
Let’s look at Example 3 again: Calculate the sum of
two numbers and display the result on the screen:
4 The problem–solving
approach
To summarise and formalise what we’ve discussed, the
following steps must be taken to find an excellent and
efficient solution.
4.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.
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?
Example:
You want to print a particular greeting to members of a
forum.
Initial planning:
Writing the algorithm in a more structured manner:
• +, -, *, /
• Initialise, set
•?=?
•x=5+y
5.
6.
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.
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.
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.
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.
Algorithm
The steps in the algorithm will be processed in the
order that they are given, one after the other, to provide
the following output on the screen:
Example 2
Problem
Enter the distance between two trees in kilometres.
Calculate and display the distance in metres and then
calculate and display the distance in centimetres.
Planning
Table 3: Input and output variables for Example 2
Description Type Variable name
Calculate centimetre
Display metre
Display centimetre
Note that the IPO chart does not contain detailed
processing steps.
Algorithm
Output:
Please provide the distance in km. 3
Distance = 3 km
Example 3
Problem
Enter the length and the width of a tennis court in
metres, then calculate and display the perimeter and
the area of the tennis court.
Planning
Table 5: Input and output variables for Example 3
Description Type Variable name
Algorithm
Trace table
The input data to test this algorithm is length = 30 and
width = 10.
enter 30
display Please enter width
enter 10
calculate 80
perim
calculate 300
area
Output:
Please enter length 30
Example 4
Problem
Enter two integers on the keyboard and calculate and
show the average of these two integers on the screen.
Planning
Table 8: Input and output variables for Example 4
Description Type Variable name
Algorithm
Example 5
Problem
Jason works as a part-time assistant in a bookshop and
receives an hourly wage. Enter the number of hours he
worked for a specific week, as well as the pay rate per
hour. He has to pay R8 towards the recreation club.
Calculate and display how much take-home pay he’s
earned for the week.
Planning
Table 10: Input and output variables for Example 5
Description Type Variable name
Calculate wage
Algorithm
The input data used to test this algorithm: hours worked
= 24 and rate of pay = R12.
Output:
Provide number of hours Jason worked 24
Example 6
Tebogo earns a monthly salary, which she divides at the
beginning of each month into amounts according to her
needs. She pays R450 on rent for her room and the
remainder of the money is divided as follows: 50% for
food, 20% for clothes, 15% for transport, 5% for
charity and the remaining amount for pocket money.
Enter her monthly salary, which is never less than R1
800, on the keyboard and then calculate and display
how much money she has available for the various
categories.
Planning
Table 12: Input and output variables for Example 6
Description Type Variable name
charity
Algorithm
Output:
Provide Tebogo’s monthly salary: 2000
Room R450.00
Food R775.00
Clothes R310.00
Transport R232.50
Charity R77.50
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
Planning
Table 14: Input and output variables for Example 7
Description Type Variable
name
save50
save100
Algorithm
Complete the following trace table:
Example 8
At the EAT-A-LOT restaurant, customers dish up their
own food and have the plate weighed in kg (2 decimal
positions). The total weight of the plate and the food
must be entered. The plate weighs 1.05 kg, which is
subtracted from the total weight. The customer has to
pay R7.35 per 100 g of food, and 14% VAT is added to
the total. Display the weight of the food in kg as well as
the amount due.
Planning
Table 16: Input and output variables for Example 8
Description Type Variable name
Algorithm
3 Calculating the outcome
of an algorithm
It is often necessary to determine the exact outcome of
a set of instructions in an algorithm or program. Usually
these statements include tricky calculations so the
programmer needs to ensure that the calculation has
been done correctly and must also know what result to
expect. This could have been done with a trace table,
but we only need to test the calculations, not the entire
algorithm, so we can use a shorter method. We’ll study
two examples to explain this method.
Example 9
A B C
A B C
A B C
33
Example 10
Use the same set of instructions as Example 9, but
change the display statement to
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.
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
Question 3
Study the following statements. Display the exact output
that will be displayed after these statements have been
executed.
3.1
3.2
3.3
3.4
3.5
Chapter 4 The selection
control structure: Part 1
Introduction
The complexity of a problem may be of
such a nature that it cannot be solved
by simply applying statements in
sequence. An algorithm may therefore
include the possibility of providing for
different options that could change the
flow of statements in the algorithm. To
enable the programmer to include this
type of logic in an algorithm, a
selection (decision) control statement,
that is based on relational and logical
operators, can be included. The
selection control structure can be a
simple if statement or a more
complicated if–then–else statement
or compound statement.
Outcomes
When you have studied this chapter you should be able
to:
determine the results of relational conditions,
evaluate expressions that contain logical
operators,
write a simple if statement in pseudocode to
test a condition,
write an if–then–else statement in
pseudocode,
prepare test data to test all possible
conditions for a program that contains
decision structures,
write algorithms containing
• simple if statements,
• if–then–else statements,
• compound if statements
• Boolean variables,
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:
16 = 5 result: false
= Equal to A= 5
Exercises
Evaluate the following expressions:
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.
Example:
Example:
X = A OR B AND C
Substitute:
X= True OR False
= False
Use parentheses:
X= (A OR B) AND C
^ Exponentiation 2 ^4 16 1
(to the power of)
\ Integer division 37 \ 5 7 4
mod Modulus 37 mod 2
arithmetic 5
= Equal to A= 5
< Less than number < 97
TRUE OR FALSE
TRUE
FALSE
FALSE OR TRUE
TRUE
Exercises
Evaluate the following expressions where A = 5, B = 7,
C = 12, D = -4, E = TRUE and F = FALSE:
Pseudocode
endif
∼the if test.
If statement syntax
Example
This algorithm can also be represented as a flowchart.
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.
Lerato bakes cakes that she sells per slice. She cuts
10 slices per cake. She calculates the amount spent on
the ingredients, electricity and packaging material. She
adds 30% to the amount spent and then she calculates
the price of a slice of cake. The user will enter the
amount spent per cake, then the algorithm will calculate
and display the price of a slice. She always sells the
slices in full Rand amounts. For example, if the
calculated price is R3.25, then the selling price will be
R4. In other words, cents are always rounded up to the
next Rand.
Planning
Algorithm
Expense R18.60
Output:
Provide the price of the cake 18.60
Example 1
Problem
Planning
Algorithm
Test the program twice using:
Planning
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.
Planning
Algorithm
Example 4
Problem
Planning
Calculate bookDays
Determine message
Algorithm
Exercises
1. In each of the following cases, do the planning
and write an algorithm to solve the problem:
1.1. The Great College offers two different
courses in Programming that are offered as self-
study courses in which the lecturer assists. The
student can decide beforehand how many weeks
he or she wants to study. The code of the first
course is A, and the code for the second is B.
You may assume that the user will only enter an
A or a B. The price for course code A is R234
per week, whereas the price for the other course
is R287.50 per week. The student has to enter
the course code and the number of weeks of
study. Calculate the total price of the course and
display the course code and total price on the
screen.
1.2. Spectators can purchase tickets to attend a
soccer match at R15 per ticket. Anyone who
buys eight or more tickets pays only R12.50 per
ticket. Prompt the user to enter the number of
tickets bought, then calculate and display the
amount due.
2. Describe the variables and write only the if
statement for the following. You may choose your
own variable names if they haven’t been
specified.
2.1. The weights of two dogs, Fluffy and Terry,
are available. Display the name of the dog that
weighs more than the other dog.
2.2. An employee’s salary, called empSalary, has
been entered. Determine and display a message
to indicate whether this person needs to pay
income tax. Only people with an income of more
than R3 000 per month have to pay tax.
2.3. Tom decided that he must have one shirt for
every pair of pants. Determine whether this is
true and display an appropriate message.
2.4. Josie wants to go to the movies, but isn’t
allowed to go unless she’s done her homework –
use a Boolean variable for this – and has R10 to
pay for the ticket. Display a message to indicate
whether she can go.
2.5. Test a student’s mark. If the mark is more
than 47, increase the mark by 2.5%, otherwise
decrease the mark by 5.7%. Display the new
mark.
3. Study the following code:
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
Example
If an employee is a Grade C employee or has worked
for the company for more than five years, a special
bonus of R1 000.00 is awarded to the employee.
Figure 4 An OR compound If statement represented
as a flowchart
Example 5
This example shows the planning for a problem with a
compound if statement.
Problem
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
Determine actFee
Display actFee
Algorithm
Exercise
Write pseudocode for the following:
Example 6
The next example illustrates the use of a Boolean
variable.
Problem
Planning
Prepare message
Exercises
1. Study the following problem statements carefully.
In each case, indicate the variables used, draw
an IPO chart and write an algorithm to solve the
problem. Do a trace table for every odd-
numbered question using carefully selected test
data.
1.1. Enter the annual salary of an employee and
also indicate whether the employee is a full-time
or part-time employee. Full-time employees pay
29.5% income tax whereas the other employees
pay 25% income tax. Calculate and display the
gross monthly salary, monthly tax payable and
the net monthly salary.
1.2. The Cheap Store sells affordable items to
customers. Provide the selling price, number of
items bought and discount percentage. The
discount only applies if a customer buys 10 items
or more. Calculate and display the discount and
the amount due by the customer.
1.3. An employee earns a basic salary of R1,200
per month. He also earns commission on sales.
The sales amount must be entered. On a sales
amount of less than R3,500 he receives 8%
commission, but if he sells more, the commission
is 12.8%. The employee pays 5% of his
commission to his manager. Calculate and
display his net income on the screen of the
computer.
1.4. Enter the distance that a participant in a
competition cycles as well as the distance the
participant swims. To earn a medal in a
competition, a participant must cycle at least 20
kilometres and swim 500 metres. Develop an
algorithm to determine if July qualified for a
medal.
1.5. Billy has to transport a number of computers
to his company. He can only load a certain
number, which must be entered, into his vehicle.
Enter the number of computers he has to
transport and, if this number is higher than the
number he can transport at the time he buys the
computers, display an appropriate message on
the screen. Also display how many computers
still need to be transported.
2. Write down only the exact output that will be
displayed after the following statements are
processed.
Hint: Use a table to enter the different values of
the variables after execution of statements to
determine the output.
3. In each of the following cases, indicate whether
the if statement is valid. If invalid, provide a
reason and rewrite it as a valid statement.
3.1. if empName = Jones then
3.2. if 12000 < empSalary < 20000 then
3.3. if newSalary > or = 25000 then
3.4. if salIncrease > 12% of Salary then
3.5. if number NOT = 20 then
3.6. if number NOT > 20 then
3.7. if number < 10 AND number > 20 then
3.8. if number < 10 OR > 20 then
3.9. if indication = True then
3.10. if number < 25 000 then
4. Rewrite each of the following statements in a
different way.
4.1. if numberA > numberB AND numberC = 10
then
numberD = number + 1
endif
4.2. if number >= 10 then
number = number + 1
endif
Chapter 5 The selection
control structure: Part 2
Introduction
Up to this point we′ve tested only one
condition in an if statement and we′ve
tested more than one condition in a
compound if statement, but it is often
necessary to test more conditions.
This chapter deals with more
complicated decision structures.
Outcomes
When you have studied this chapter, you should be able
to:
write a nested if statement in pseudocode,
write a select case statement in pseudocode,
write algorithms containing
• nested if statements, and
• select case statements.
1 Nested If statements
Study the following if-then-else statement:
Note
To initialise a value means assigning a zero to numeric
values and spaces to non-numeric values.
Note that if the value is not equal to 5.2 or is not equal
to 6, the values of A and B will not change.
Table 2: Test 1
Instruction A B Outcome of if
Assign 5.2 25
If A = 5.2 True
If B > 20 True
Calculate 10.2
Table 3: Test 2
Instruction A B Outcome of if
Assign 5.2 15
If A = 5.2 True
If B > 20 False
Calculate 11.5
Table 4: Test 3
Instruction A B Outcome of if
Assign 6 100
If A = 5.2 False
If A = 6 True
Assign 0
Assign 0
Table 5: Test 4
Instruction A B Outcome of if
Assign 8.3 21
If A = 5.2 False
If A = 6 False
In Test 4, the value for A will remain 8.3 and the value
of B 21.
Example 3
The variables A, B, K and Z are integers.
Example 4
The Bright Light Company is increasing the salaries of
its employees according to which department they work
in, as shown in Table 7.
Table 7: Percentage increases by department
Department code Percentage increase
A 7.2
B 6.8
Planning
Table 8: Input and output variables for Example 4
Description Type Variable name
Display monSalary
Algorithm
Output:
Provide the department code: A
<5 1.0
5–8 0.9
> 8 – 12 0.75
> 12 0.6
The user must enter the name of the dog and the
weight of the dog in kilograms (to the nearest 500 g).
Then the algorithm must calculate and display the daily
dosage to be administered to the dog, as well as the
dog′s name.
Planning
Table 11: Input and output variables for Example 5
Description Type Variable name
Calculate dosage
Algorithm
Comment 1
Each of the if statements tested only one condition, for
example, the second if statement:
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.
Output:
Provide the name of the dog: Fluffy
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.
S 200
M 260
L 400
Planning
Table 14: Input and output variables for Example 6
Description Type Variable name
Validate data
Calculate amtDue
Display amtDue
Algorithm
In addition to testing a normal transaction, we
should test incorrect data. We′ll include a non-
existent car type as well as a non-numeric value
for the number of days. We′ll also include a
small car to test the special offer.
Small 4
Large 3
Grand 9
Medium K
Output:
Enter the type of car you need S, M or L: S
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.
5 8
-5 -6
-3 -3
10 5
750 g R21.95
1kg R29.83
0 – 20 0
21 – 50 10
51 – 100 40
Planning
Table 21: Input and output variables for Example 9
Description Type Variable name
Calculate minutes
Algorithm
Test data: Pages = 45, 432, -6, 255, 16
Output:
Enter the number of pages read: 45
Good girl! You may watch TV for 10 minutes.
Exercises
1. Write only the select case statements for the
following problem statements.
1.1. If the value of K is equal to 3, increase the
value of A by 5%. If the value of K is equal to 4,
decrease the value of A by 8. If the value of K is
equal to 7, add the value of B to the value of A,
otherwise decrease the value of A by 12%.
1.2. If the integer variable called xyz contains a
value of 3, 8 or 9, display three asterisks, but if
xyz contains a negative value, display five
asterisks. However, if the value is between 10
and 20, then display seven asterisks. If xyz
contains any other value, display four equals
signs.
1.3. Change the value of the variable called X
based on the value of A, as given in Table 23. A
and X contain positive values; X is a variable with
a real value and A is variable with an integer
value.
D = divorced W = widowed
0 - 5 000 0
0–2 R20.00
5.2.
5.3
5.4.
Chapter 6 Iteration using a
fixed count loop
Introduction
Programming often involves repeating
a set of instructions a number of times.
Sometimes we know exactly how many
times we need to repeat the
instructions, and other times we don’t.
This type of programming is called
iteration or looping. In this chapter,
we’ll discuss the for loop where we
know exactly how many times to
repeat a set of instructions. This is
sometimes called a fixed count loop
or an automatic count loop.
Outcomes
When you have studied this chapter, you should be able
to:
write a loop in pseudocode using a for-next
statement,
explain the purpose of an accumulator and
implement it in a solution, and
know when to display output during every
execution of a loop and when to display it at
the end of the loop.
Example 1
A for-next statement is used to display the consecutive
numbers from 1 to 10.
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
Figure 2 Flowchart of the For-next statement with a
negative step
Questions
What will the output of the following for-next loops be?
Example 3
The sum of the first five odd numbers is calculated and
displayed.
People often think that they don’t need the sum until just
before the processing ends, so they plan to calculate
the sum just before it’s needed. But it simply doesn’t
work that way!
Right at the end, only the last odd number is available.
So whenever the number – in this case, the next odd
number – is available, it must be added to the sum.
Every number will be available in the current execution
of the loop.
assignment 0
assignment 1
for 1
calculation 1
calculation 3
for 2
calculation 4
calculation 5
for 3
calculation 9
calculation 7
for 4
calculation 16
calculation 9
for 5
calculation 25
calculation 11
for 6
Example 4
The first six multiples of 5 (starting at 5) are displayed,
as well as their sum.
Algorithm
Next we’ll test the algorithm using a trace table.
Example 5
Eight integers between 5 and 48 are entered and the
average of these numbers is displayed.
Algorithm
Example 6
This example shows the planning and an algorithm to
display a series of even numbers. These two questions
must be asked of the user:
At what even number do you want to start?
How many even numbers do you want to display?
Planning
Table 3: Input and output variables for Example 6
Description Type Variable name
Display evenNo
Algorithm
Test the logic with the following four sets of test data:
beginNo = 8, howMany = 10
beginNo = 9, howMany = 15
beginNo = x, howMany = 3
Output:
8 10 12 14 16 18 20 22 24 26
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
Method 2
Algorithm
Test the logic using this test data.
Bill 67
Don 92
Dave 28
Sonny 62
Edith 54
Bob 34
Robbie 43
Cassandra 64
Julie 78
Output:
The name of the student who obtained the
highest mark is Don
Planning
Table 7: Input and output variables for Example 8
Description Type Variable name
Enter totNumber
Display result
Algorithm
Output:
The number can be divided by five 108 times
Weight of parcel in kg
Parcel x of y
Examples
Assume a 5 has been entered as a
positive integer number. The output may
be one of the following, depending on the
choice made.
Note
The factorial is the product of all
consecutive positive numbers up to this
number:
1 x 2 x 3 x 4 x 5 = 120
10.2
Example 9
A structure like these loops is called a nested loop.
i j
1 1
1 2
1 3
2 1
2 2
2 3
It is clear that the inner loop will move through all the
counts before the index in the outer loop increments the
counter – and then the inner loop starts again from the
beginning.
Example 10
Four students in a class wrote three tests each. The
average of the three tests will provide the final mark for
the student. Display the final mark for each student as
well as the class average on the screen.
Planning
Table 9: Input and output variables for Example 10
Description Type Variable name
Display finMark
Calculate average
Display average
Algorithm
Tests 1 2 3
Students 1 45 50 55
2 63 68 71
3 23 34 31
4 41 61 59
Exercises
1. Code an algorithm, using nested for-next loops,
to draw the following figure:
1
12
123
1234
12345
123456
1234567
12345678
123456789
You may display only one digit per statement and
may not repeat any of the statements – it must
be coded effectively!
Hint: The maximum for the counter in the inner
for-next loop must be the same as the current
counter in the outer for-next loop.
2. In each case, predict the output of the
pseudocode.
2.1.
2.2.
2.3.
2.4.
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.
Example 1
This example calculates the sum of all the consecutive
integers starting at 24 while the sum is less than 23456.
It then displays how many integers have been added to
the sum.
Once again, to yield the correct results, it is important
to understand which statements must be done before
processing the loop, which statements must be inside
the loop and which statements must be placed after the
loop.
Comment 1
These statements prepare the variables before entering
the loop. They initialise the variables with the correct
starting values.
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.
Planning
Table 1: Input and output variables for Example 2
Description Type Variable name
Input Name of fisherman String fmName
Determine winner
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.
Johnny 2
Kevin 7
Fred 10
Bill 5
Ted 12
Paul 9
Output:
Provide the number of fish caught by the first
fisherman
:
Provide the number of fish caught by the next
fisherman
Congratulations Ted!!!
Example 3
Alexis went shopping and bought a number of different
items. We need to enter the amount of money in her
purse and the price of each item to calculate the total
amount. After all the prices are entered, a price of 0
(zero) is entered as a sentinel to indicate that she has
finished selecting items to buy. If the total amount she
spent is more than R100 she’ll receive a discount of
3.5%. If the money in her purse is enough to pay for her
shopping, we need to calculate and display how much
money she will have left in her purse after she’s
received her change, if any. If she doesn’t have enough
money to pay for all the items, a message is displayed
indicating how much more money she needs to pay for
her shopping.
Planning
Table 3: Input and output variables for Example 3
Description Type Variable name
Calculate total
Test purseMoney
Display results
Algorithm
Item 1 R150.50
Item 2 R285.70
Item 3 R397.42
Desk checking:
Data set 2
Item 1 R3.00
Item 2 R25.50
Item 3 R21.60
Item 4 R7.80
Desk checking:
Output:
Alexis needs R94.89 more to pay for her
purchases
Planning
Table 5: Input and output variables for Example 4
Description Type Variable name
Count noTimes
Accumulate totWeight
Algorithm
Test data
Possible input values with respective output results:
2. Examples of flowcharts
for pre-test and post-test
loops
The two flowcharts shown here set out the logic for
entering the marks of 10 students, then calculating and
displaying the average of their marks. The first
flowchart shows this being done with a pre-test loop
(do-while) and the second shows a post-test loop (do-
until). In both cases, the marks for all students are
entered and accumulated in the loop and the average is
calculated and displayed at the end of the loop.
Figure 1: Flowchart representing a Do-while loop
The loop in Figure 1 is clearly a pre-test loop because
the condition is tested in the beginning and the
statements in the body of the loop will be executed only
while the condition is true. If the condition is not true the
first time, the loop will not execute at all.
Figure 2: Flowchart representing a Do-until loop
Exercises
1. Write an algorithm to calculate and display the
sum of the first n numbers of the following series:
(Enter a value for n.)
1.1. 1, 1, 2, 3, 5, 8, 13, 21, …
1.2. 1, 2, 4, 7, 11, 16, …
Determine the output of the following
algorithms.
2.1.
2.2.
2.3.
2.4.
2.5.
3.2.
AY 6%
HT 6.3%
KL 6.9%
Men R65.50
Ladies R56.80
A R50.00 R30.00
B R62.50 R36.25
C R74.87 R40.50
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,
1 Properties of arrays
An array consists of a number of related variables, and
has the following properties:
Array name
The name of an array must be descriptive. Examples:
Element
One element in an array is a single variable that
contains a value at a given time. Examples:
Data type
All the elements in an array must be of the same data
type, such as String or Integer. Examples:
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.
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.
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
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.
Example 1
Problem
Continuing with the CalculateFinalMark problem, the 10
test marks for the student must be stored in an array,
then the average of the 10 test marks must be
calculated to determine the student’s final mark. After
the final mark has been calculated, all the marks as well
as the final mark must be displayed.
Planning
Table 2: Input and output variables for Example 1
Description Type Variable/array
name
Algorithm
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
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%
Example 3
Problem
The identity numbers of the eight employees in a
particular company are stored in an array. The manager
wants to know if a specific woman is a company
employee by entering her identity number.
Algorithm
Example 4
An array called evenNumbers, which has 44 elements
with consecutive even numbers starting at 14, needs to
be filled.
Algorithm
We can then modify the example to start at any
even number.
Algorithm
Example 5
Problem
An array called noInStock already contains the following
valid positive integer values in the 20 elements
4, 15, 38, 53, 8, 95, 129, 653, 45, 658, 12, 40, 0, 98,
74, 32, 9, 39, 25, 87
Algorithm
Output:
The highest value in the noInStock array is: 658
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:
4
5
0 ab3 0 chair
1 kh8 1 table
2 vs1 2 bed
3 gp5 3 cupboard
4 wd4 4 sofa
Example 6
Problem
We need to write an algorithm to enter a code, find the
corresponding description and then display the
description on screen. If the description is not found
because code doesn’t contain the entered code, a
suitable message must be displayed.
Algorithm
Exercises
Do the planning and write algorithms to solve each of
these problems:
75 Chocolate 5.75
23 Soda 6.25
41 Burger 15.85
17 Muffin 5.75
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:
4 22
5 23
3 21
2 24
3 19
6 25
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.
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
Exercises
Do the planning and write algorithms to solve each of
the following problems:
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).
15
36
20
15
Ascending: A to Z
Descending: Z to A
47
16
17
47
16
17
16
47
17
16
47
17
25 At this stage, you will notice that the highest value (47) is in the
last position.
16
17
47
16 Compare the first two elements: 25 is greater than 16. Values are
swapped.
25
17
47
16 Comparing the next two elements: 25 is greater than 2. Values are
swapped.
25
17
47
17
25
47
Example 8
Problem
An array called petNames has 15 elements, each of
which contains the name of a pet. The values of the
elements must be sorted in ascending sequence. In this
example the bubble sort method is used to achieve the
sequence.
Algorithm
Example 9
Now let’s sort the petNames array we used in Example
8 in descending order.
Note that (n – 1) exchanges will take place if there are
n elements in the array. In this example the selection
sort method is used to achieve the sequence.
Algorithm
Exercises
1. Twenty athletes took part in a race and their
times in minutes were stored in an array as real
numbers. Use a bubble sort to sort the times (in
ascending or descending order, depending on
your logic) and then display the times of the
fastest three athletes (lowest times).
2. Repeat Question 1 to include a parallel array that
contains the names of the athletes. When doing
the bubble sort, remember to swap the names in
the names array at the same time that you swap
the times in the times array.
3. An array called numberArray contains an odd
number of integer values. Use a selection sort to
sort the array in ascending order, then display
the smallest (first) value, the middle value and the
largest (last) integer. Enter the number of
elements in the array in the beginning of the
program, as well as the values of the elements.
Chapter 9 Function
procedures and
subprocedures
Introduction
Using function procedures and
subprocedures enables you to split
large, complex algorithms into smaller
modules , which makes the computer
coding more effective. Lines of code
that perform a specific task that is
repeated often would typically be
coded as a separate procedure. Such
a procedure is written just once and
reused whenever the task needs to be
performed.
Outcomes
When you have studied this chapter you should know
and understand the following:
modules and modularisation,
drawing a hierarchy chart,
the purpose and use of value parameters and
reference parameters,
the use of function procedures,
writing a statement to call a function, and
writing the corresponding function header,
statements in the loop and a statement to
return an answer,
writing functions with and without parameters,
the use of subprocedures,
writing a statement to call a subprocedure,
and writing the corresponding subprocedure
header and statements in the subprocedure,
and
writing subprocedures with or without
parameters.
1 Modules and
modularisation
Modularisation divides the solution to a problem into
smaller pieces – called modules – to improve the
flexibility of a program and shorten its development
time. A module is therefore part of a program. Large
and complex programs can be divided into
independently developed modules. Each module is
made up of one or more statements to perform a
specific task. The various modules are then linked to
form a working program.
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.
3 Parameters
Before we can study function procedures and
subprocedures, we need to understand what
parameters are. A parameter is data (variables or
values) that is sent to a function or a subprocedure,
which it needs to perform the task it has to do. A
parameter may also contain the address of an answer
when dealing with a subprocedure.
There are two types of parameters:
An assignment statement
Send two values, number1 and number2, to a function
named CalcSum, which will calculate the sum of the two
numbers.
A display statement
Use the same example, but don′t store the answer in
sum; instead display the sum of the two numbers.
An if statement
if CalcSum(number1, number2) > 40 then
display “The sum is greater than 40”
endif
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:
return total
Important notes
The function name used in the calling statement and
the function name in the function header must
always be the same.
The names of the arguments and parameters need
not be the same.
The order of the variables in a calling statement′s
argument list and the parameters in the function
header must always be the same.
The number of variables in a calling statement′s
argument list and the number of parameters in the
function header must always be the same.
The name of the value returned by the function need
not be the same as in the calling statement.
The arguments are only the names of the applicable
variables in the calling module. On the other hand,
the parameters in the header must indicate whether
the parameter is a value parameter or a reference
parameter – in other words, whether a copy or an
address has been sent.
The function can also be written as follows, where the
variable total is replaced by the expression valNumber1
+ valNumber2.
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.
Planning
Table 1: Input and output variables for Example 1
Algorithm
Important notes
This example illustrates that the function and the
main program are two completely separate entities.
The main program and the function communicate
using parameters.
If the function does not receive the number and the
price, it will not be able to calculate the correct
answer. This is because number and price are local
to the main module where they have been declared
and cannot be accessed by the function unless the
function receives them as parameters.
If the amount due is not returned to the main
procedure, the main procedure will not have the
correct value to display.
The parameters in the call statement′s argument list
(in the main procedure) are in the same order as the
parameters in the function header′s parameter list.
In most programming languages, the functions and
subprocedures are coded before the main program,
so this book will follow that convention in the
example algorithms.
Example 2
Write an algorithm to enter three test marks for a
student. A function is called to calculate the average
mark. Another function is used to indicate whether the
average mark is a pass mark (>=50) or a fail mark. The
average as well as the result must be displayed on the
screen. All input and output must be done in the main
procedure.
Planning
Table 2: Input and output variables for Example 2
Algorithm
Exercises
1. Identify and correct all the errors in the following
function call and its corresponding function
header.
decPay = CalcPay(Hours, Tariff )
Function Pay(refTariff, valHours)
2. Determine the output of each of the following
algorithms:
2.1.
2.2.
0 – 15 Starvation
> 25 – 30 Overweight
> 30 – 40 Obese
1–7 No discount
8 – 20 2.5%
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.
Planning
Table 5: Input and output variables for Example 3
Description Type Variable name
Main procedure
(EarnInterest)
Subprocedure
(CalcNewValues)
Parameters Copy of interest Real valRate
rate
Subprocedure
(AccSum)
Subprocedure
(DisplayResults)
Algorithm
Example 4
This example shows the planning and an algorithm to
calculate the final marks students obtained for
Programming 3. The final mark is calculated on the
marks of various assessments and their particular
weightings:
Test 1 15%
Test 2 20%
Examination 50%
Planning
Table 7: Input and output variables for Example 4
Description Type Variable name
Main procedure
(CalcFinalMark)
Output None
Function
(CalcClMark)
Subprocedure
(CalcValues)
Subprocedure
(DisplayResults)
Algorithm
Important note
As mentioned earlier, a function or subprocedure can be
called from a main procedure or from any other function
or subprocedure. In Example 4 a function was used to
determine the better class test and a subprocedure
was used to determine the result. A second
subprocedure is called from this subprocedure to
determine and display the result. This can also clearly
be seen from the hierarchy chart.
Example 5
A function is called to enter the discount that applies to
a product. The discount may never be more than 25%.
Exercises
1. What will the exact output be after each of these
program segments has been executed?
1.1.
1.2.
2. An athlete runs a long distance from one town to
another. In the main algorithm, enter the name of
the athlete, the distance between the two towns
and the actual distance that the athlete can run
per day. Call a subprocedure to calculate the
number of days the athlete will need to run the
entire distance between the two towns. Display
the answer in the main algorithm.
Rewrite your solution, but call a function instead
of a subprocedure.
3. Study each of these subprocedure calls, then
write the complete subprocedure for the required
algorithm.
3.1. Call SortTests(test1, test2, test3)
The subprocedure must place the best test
mark in the first parameter, the second-
best test mark in the second parameter
and the lowest mark in the third
parameter.
3.2. Call CalcNetSal(GrossSal, 23.5,
TaxAmt, cNetSal)
The subprocedure must receive a gross
salary and a tax percentage (23.5%, in
this case). It must then calculate the tax
amount for the employee, then the net
salary by deducting the tax amount from
the gross salary. All values will be
applicable to a month′s salary. The tax
amount and net salary must be available to
the calling module after they′ve been
calculated.
English 3 English 4
APS 22 APS 19
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.
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,
2 Opening a sequential
access file
Every file that is used in the program must be opened
before it can be used. The open statement, which
contains the name of the file, will try to find the
specified file. When the file is found, it will connect this
external physical text file to the filename used in the
program in order to use it in the program.
Input file
open input(name of file)
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.
3 Closing a sequential
access file
A file should be closed as soon as possible to prevent
loss of information. In the case of an input file, it must
be closed as soon as all the text has been read from it
and, when using an output file, as soon as all the text
has been written to it.
In cases where quite a number of files are used at
different stages in the program, it is very important to
adhere to this rule by keeping open only the files that
are in use. It is also essential that files are opened just
before their data is needed, and not before.
close(name of file)
Example: close(employees.txt)
read(name of file)
Example 1
In this pseudocode example, lines of text are read from
the employee file. Every line of text is then displayed.
The process is repeated until the end of the file is
reached.
Note that the first line of text is read before the loop.
The current line of text is displayed inside the loop, and
the next line of text must be read before the next
execution of the loop. If this next read statement is
omitted, the first line of text will keep on being displayed
because the next line is never read and the end of file
will never be encountered. Each read statement
accesses the next line of text and tests whether the end
of the file has been reached.
23456*Nkosi.S.A.*Purchases*Assistant#
33445*Pillay.N.*HR*Assistant#
41231*Mokoetsi.M.M.*Marketing*Officer#
:
5 Writing information to a
sequential access file
As mentioned earlier, text lines can be added to an
existing file or a new output file can be created. The
open statement indicates the way to write to the file.
write(name of file)
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.
12345*Boyd.R.S.*Sales*Manager#
23456*Nkosi.S.A.*Purchases*Assistant#
33445*Pillay.N.*HR*Assistant#
41231*Mokoetsi.M.M.*Marketing*Officer#
:
6 Reading from and writing
to the same sequential file
If lines in a sequential file need to be modified, the only
way to do this is to read all the records into an array,
manipulate the array elements, then write the array
back to the file by recreating the file.
Example 3
Let’s say we need to change either the job description
or department of particular employees.
Initial planning
Accept the
employee number
Check if it exists in
the array
Ask if job
description must be
changed
Ask if department
must be changed
If job description
must be changed
If department must
be changed
needs to be changed
Algorithm
Exercises
1. Indicate whether the following statements are
true or false. Provide a reason for your answer.
1.1. An input file should be closed as soon
as all data has been read from it.
1.2. It is possible to write data to a
specific position within other data in an
input file.
1.3. Every file that is used in the program
must be opened before it can be used.
1.4. In an algorithm to read data from a
file, the following code is correct:
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.
C++
Delphi
Smalltalk
Java
Outcomes
When you have completed this chapter, you should be
able to:
understand the basic concepts of object
orientation,
understand the importance of encapsulation
and information hiding,
distinguish the relationships between classes,
and
follow the basic steps of object oriented
design.
1 Concepts of object
orientation
Most of the concepts in procedural languages also
feature in most OO languages. Sometimes an OO
language may refer to a familiar concept in a different
way, but it will still be the same concept. For example,
variables, procedures, invocation of procedures and
passing parameters to and from procedures are
concepts common to both types of programming
languages. Control structures like sequence, selection
and iteration structures also feature in OO languages.
However, in object orientation there is a whole new set
of concepts, which we’ll introduce now.
1.1 Objects
The real world is full of objects, such as motor cars,
dogs, cities, people, customers, cash registers, and so
on. We can also consider an object to be a container
for data, with attributes, and the operations needed to
manipulate that data. Objects function well as software
modules because they can be created, used and
maintained independently of one another.
Figure 1 shows an object with properties, or attributes,
and operations, or methods.
Interact with other objects Interact with other humans and things
1.2 Properties
Objects often need to hold information about
themselves. Let’s use an object called Bob as an
example. Bob needs to know his name, age, gender,
and so on. We refer to these items as the object’s
properties or attributes. Each of these properties
normally has a scope, a type and a value, just as
variables in the procedural approach do. The scope of
an attribute can be private or public. An attribute that
has a private scope is visible only inside the object it
applies to. This means that the private attributes of an
object are not visible to other objects within the same
system. A property that has a public scope is visible
within the object it applies to as well as to other objects
within the same system.
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.
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.
Type String
Make String
Model String
Colour String
You can see that the two instances of the class Car
have the same attributes, but different values.
2 Encapsulation and
information hiding
In the object-oriented approach, classes, and therefore
also objects of that class, are similar to black boxes
with a clearly defined interface. This interface is the
only mechanism that other objects can use to
communicate with the object.
Class: Sorter
Attributes
Operations
3 Design notations
Three people who have done a lot of work in the OO
design notation area are James Rumbaugh, Grady
Booch and Ivar Jacobson. At first, each of them had
their own method of representing an OO design. Not
only were the representations different, the underlying
theories of object behaviour and interaction were also
different. A couple of years ago, Rumbaugh, Booch and
Jacobson conceived of the Unified Modelling Language,
or UML. UML enables the designer to represent
classes, with their attributes and operations, as well as
the relationships between classes.
4 Relationships between
classes
The relationships between classes fall into three
categories:
association,
aggregation, and
inheritance.
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.
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.
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.
5 More concepts
This chapter is a basic introduction to OO, but you
should know that there are some advanced concepts
that we have not covered here. These include abstract
classes, polymorphism, overriding and overloading.
6 Designing an object-
oriented solution
The object-oriented approach is about far more than
just a couple of new programming structures and
techniques. As we mentioned before, it’s a whole new
way of thinking. This means that objects are not only
part of the programming of a system but are used right
from the start during the analysis and design phases.
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.
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.
1 Pseudocode
Example 1
Write an algorithm to enter two numbers that are not
equal and display the bigger number.
Example 2
Write an algorithm to enter integers between 5 and 20
and accumulate their sum until it exceeds 200. Display
how many integers were entered.
2 Flowcharts
A flowchart is a schematic representation of an
algorithm. It illustrates the steps in a process and it
consists of a number of specific diagrams joined in a
specific manner. It graphically represents the program
logic by using a series of standard geometric symbols
and connecting lines. Different flowchart symbols are
used for different aspects of the process.
Flowchart symbols
Terminal
This symbol indicates the starting or stopping point in the
logic. Every flowchart should begin and end with this
symbol.
Input/Output
This symbol represents an input or output process in the
algorithm, such as reading, writing and displaying.
Processing
This symbol is used for types of processing, such as
arithmetic statements and assigning values.
Decision
This symbol is used to compare variables/values that may
change the flow of the logic. It may cause the logic to
branch in another direction.
Module
This symbol represents another module that must be
processed. This module will have its own flowchart.
Connector
The connector joins two parts of the flowchart, e.g. from one
page to the next page.
Connecting lines
These lines connect flowchart symbols with one another.
Example 1
Draw a flowchart to enter two numbers that are not
equal, and display the bigger number.
Figure 1 Flowchart for Example 1
Example 2
Draw a flowchart to enter integers between 5 and 20
and accumulate their sum until it exceeds 200. Display
how many were entered.
Figure 2 Flowchart for Example 2
3 Nassi-Shneiderman
diagrams
A Nassi-Shneiderman diagram (or NSD) is a graphical
representation for structured programming. Developed
in 1972 by Isaac Nassi and Ben Shneiderman, these
diagrams are also called structograms, because they
show a program’s structures. Everything you can
represent with a Nassi-Shneiderman diagram you can
also represent with a flowchart.
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.
Example 1
Draw a Nassi-Shneiderman diagram to enter two
numbers that are not equal, and display the bigger
number.
FindTheBigger
Figure 3 Nassi-Shneiderman diagram for Example 1
Example 2
Draw a Nassi-Shneiderman diagram to enter integers
between 5 and 20 and accumulate their sum until it
exceeds 200. Display how many were entered.
CountTheNumber
Figure 4 Nassi-Shneiderman diagram for Example 2
Appendix B Error handling
and debugging techniques
Introduction
Beginners aren’t expected to write
flawless programs! The best way to
learn to program without errors is to
practise, practise and, once more,
practise. It is said that practice makes
perfect!
Outcomes
When you have studied this appendix, you should be
able to:
distinguish between different types of errors
and
use a trace table to test the correctness of
the program logic before the program is
coded in a programming language
1 Types of errors
enter number
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.
Algorithm
To create a trace table we need an instruction column,
a column for each of the variables and a column for the
output (which will be shown on the screen).
enter 4
enter 5
calculate 20
Algorithm
enter 20
if False
if False
calculate 500
Exercises
Write the algorithms and then create trace tables for
each of the problems to test the algorithm for
correctness.