Uploaded by Charmaine Indurjeeth

Basic Programming Principles by CM Pretorius

advertisement
2nd Edition
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
text in a simple and straightforward manner. It contains many examples and exercises with
explanations and answers that promote understanding. New exercises provide opportunities
for students to apply the principles of programming and problem-solving, and learning
outcomes highlight the key learning areas. It is an update of Basic Programming Principles:
Using Visual Basic.Net 2nd edition without reference to the Visual Basic.Net.
The book covers:
•
general programming concepts and calculations
•
understanding problems and planning solutions
•
writing algorithms in sequential steps
•
the selection control structure
•
iteration using a fixed count and do-loop
•
functions and procedures
•
array processing
•
sequential text files and
•
introduction to object-oriented programming concepts.
Basic Programming Principles
2nd Edition
CM Pretorius and HG Erasmus
Basic Programming Principles
Basic Programming Principles
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.
CM Pretorius and HG Erasmus
Basic Programming_PRINT_281112.indd 1-3
2012/11/28 11:48 AM
Pearson Education South Africa (Pty) ltd
Forest Drive, Pinelands, Cape Town
www.pearsoned.co.za
Copyright © Pearson Education South Africa (Pty) Ltd 2012
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted
in any form or by any means, electronic, mechanical, photocopying, recording or otherwise without the
prior written permission of the copyright holder.
First published 2012
ISBN: 9781775786030
Publisher: Juanita Pratt
Managing editor: Amelia van Reenen
Editor: Rachel Bey-Miller
Proofreader: Careena Koch
Indexer: Ellen du Toit
Book design: Christopher Davis
Typesetting and DTP work: Lizette van Greunen
Cover design: Flame Design
Cover artwork: Corbis
Printed by:
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
BPP intro.indd 2
2012/11/26 6:53 PM
iii
Preface
In the world of information technology, a thorough knowledge and
understanding of problem-solving and basic programming principles are vital
necessities.
The programming language used to solve the problem does not usually
matter to the end user. However, the information needs to be reliable, user
friendly and correct in order to assist the end user in the decision-making
process. Therefore, the process of problem solving is imperative.
This book focuses on the basic principles of problem solving. Various
problems have been supplied and the subsequent steps to develop solutions
have been provided and discussed in detail. The authors followed a step-wise
approach to solving problems, including the following:
•
•
•
•
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.
BPP intro.indd 3
2012/11/26 6:53 PM
iv
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!
BPP intro.indd 4
2012/11/26 6:53 PM
v
Contents
BPP intro.indd 5
Chapter 1
General concepts and arithmetic
Introduction
1
Data hierarchy
1.1
Character
1.2
Field
1.3
Record
1.4
File
1.5
Table
1.6
Database
1.7
Data warehouse
2
Variables
2.1
Naming a variable
2.2
Types of variables
2.3
The value of a variable
3
Constants
4
Using variables in expressions and assignments
5
Arithmetic expressions
5.1
Key words used in arithmetic expressions
5.2
Arithmetic expressions and equations
5.3
Arithmetic operators
5.4
Setting up arithmetic equations
5.5
Examples using variables and constants
1
1
2
2
3
3
3
3
3
4
4
4
5
7
8
8
9
9
10
11
13
14
Chapter 2
Understanding a problem and using a computer to solve it
Introduction
1
Problem solving
2
Understanding the problem
3
Data processing
4
The problem-solving approach
4.1
Analyse the problem
4.2
Identify alternative ways to solve the problem
4.3
Select the most effective way to solve the problem
4.4
List all the steps
4.5
Evaluate the algorithm for accuracy
4.6
Pseudocode
4.7
What does pseudocode entail?
4.8
Writing an algorithm
18
18
18
19
23
24
24
25
25
26
26
26
28
29
2012/11/26 6:53 PM
vi
BPP intro.indd 6
Chapter 3
Write algorithms in sequential steps
Introduction
1
Program planning
2
Testing the logic of an algorithm
3
Calculating the outcome of an algorithm
31
31
31
36
46
Chapter 4
The selection control structure: Part 1
Introduction
1
Relational operations
2
Logical operations
3
The simple If statement
3.1
Testing a program that has an If statement
3.2
Examples of simple If statements
4
The If-then-else statement
4.1
Examples of If-then-else statements
5
Compound If statements
6
Data validation
52
52
53
54
57
59
62
66
67
71
77
Chapter 5
The selection control structure: Part 2
Introduction
1
Nested If statements
1.1
Nested If statements in programs
2
The Select Case structure
80
80
81
87
98
Chapter 6
Iteration using a fixed count loop
Introduction
1
The For-next loop
2
Nested For statements
110
110
110
128
Chapter 7
Iteration using the Do loop
Introduction
1
The Do loop
1.1
Pre-test loop (Do-while statement)
1.2
Post-test loop (Do-loop-until statement)
1.3
Terminating execution of a loop
1.4
Examples of Do-while loops
1.5
Examples of Do-until loops
2.
Examples of flowcharts for pre-test and
post-test loops
133
133
133
134
135
135
136
142
144
2012/11/26 6:53 PM
vii
Chapter 8
Arrays
Introduction
1
Properties of arrays
1.1
Advantages of using a one-dimensional array
2
Parallel (paired) arrays
3
Two-dimensional arrays
4
Sorting arrays
4.1
The bubble sort method
4.2
The selection sort method
153
153
154
156
169
171
176
177
179
Chapter 9
Function procedures and subprocedures
Introduction
1
Modules and modularisation
2
Hierarchy charts
3
Parameters
3.1
Value parameters
3.2
Reference parameters
4
Function procedures
4.1
The function call
4.2
The function
4.3
Calling a function and using a function
5
Subprocedures
5.1
The subprocedure call
5.2
The subprocedure
5.3
Calling an independent subprocedure and
using a subprocedure
5.4
Functions and subprocedures without parameters
181
181
182
182
183
183
183
184
184
185
187
193
193
193
Chapter 10 Sequential text files
Introduction
1
Input and output files
2
Opening a sequential access file
3
Closing a sequential access file
4
Reading information from a sequential access file
5
Writing information to a sequential access file
6
Reading from and writing to the same
sequential file
BPP intro.indd 7
194
199
205
205
206
206
207
208
212
214
2012/11/26 6:53 PM
2nd Edition
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
text in a simple and straightforward manner. It contains many examples and exercises with
explanations and answers that promote understanding. New exercises provide opportunities
for students to apply the principles of programming and problem-solving, and learning
outcomes highlight the key learning areas. It is an update of Basic Programming Principles:
Using Visual Basic.Net 2nd edition without reference to the Visual Basic.Net.
The book covers:
•
general programming concepts and calculations
•
understanding problems and planning solutions
•
writing algorithms in sequential steps
•
the selection control structure
•
iteration using a fixed count and do-loop
•
functions and procedures
•
array processing
•
sequential text files and
•
introduction to object-oriented programming concepts.
Basic Programming Principles
2nd Edition
CM Pretorius and HG Erasmus
Basic Programming Principles
Basic Programming Principles
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.
CM Pretorius and HG Erasmus
Basic Programming_PRINT_281112.indd 1-3
2012/11/28 11:48 AM
1
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.
Ed 3 BPP 4th pgs.indb 1
2012/11/26 2:45 PM
2
•
BASIC PROGRAMMING PRINCIPLES
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:
Data warehouse
Largest
Database
⇑
File and table
⇑
Record
⇑
Field
⇑
Character
Smallest
Table 1: The data hierarchy
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.
Ed 3 BPP 4th pgs.indb 2
2012/11/26 2:45 PM
GENERAL CONCEPTS AND ARITHMETIC
•
3
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.
EmployeeID
Surname
First Name
Job title
Pay Grade
Fulltime?
DGS021
Bavuma
Charles
Foreman
7
True
DGS022
September
Jontie
Carpenter
5
True
DGS023
Tanda
Goodwill
Carpenter
5
False
Table 2: A sample table
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
Ed 3 BPP 4th pgs.indb 3
2012/11/26 2:45 PM
4
•
BASIC PROGRAMMING PRINCIPLES
results, one containing students’ personal details, and a third containing details
about the students’ lecturers.
Depending on how a company processes data, they may opt to use files, or
tables and databases, or a combination of these.
1.7 Data warehouse
A data warehouse is the largest structure used to collect and store data for
processing, analysis and reporting. It may consist of several databases.
2 Variables
Programmers use the term ‘variable’ to refer to a position or location in the
memory of the computer where a value can be stored. Initially, the variable
need not contain a value. The word variable indicates that the value of the
variable may vary as needed, or as processing is done. You can visualise a
variable as a box in memory that contains one and only one specific value at a
given time.
2.1 Naming a variable
Every variable is given a descriptive name. There is no need for the programmer
to know the exact position (address) of the variable, because the compiler will
link the given name of the variable to the actual address in memory. When
solving a problem, only one name is given to a variable and this exact name is
used all the time.
When choosing a name for a variable, the programmer must adhere to
certain rules. These rules may differ between programming languages, but for
the purpose of this book the following apply:
1. The name must be unique. While solving a problem, two variables may
not have the same name.
2. The name must be descriptive – for instance, a student’s grade should be
called grade, whereas the mark the student gets should be called mark.
3. The name may not contain spaces, but more than one word can be joined
to form a name. For instance, the number of pages in a book could be
called bookPages and the price of an item could be called itemPrice. The
underscore character can also be used to join words in a variable name.
4. A name can contain letters and numbers, such as department23, but cannot contain only numbers.
5. A variable name must start with a letter; it cannot start with a number.
6. A variable name may not contain special characters, such as &, # and @.
7. A variable name should be as short as possible, while remaining descriptive.
Ed 3 BPP 4th pgs.indb 4
2012/11/26 2:45 PM
GENERAL CONCEPTS AND ARITHMETIC
•
5
2.1.1 How to name a variable
The convention is to use only lower-case letters in the name of a variable,
except where two or more words are joined. In such cases, all the following
words start with an upper-case letter, which is known as camel casing.
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
Table 3: Examples 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
2.2 Types of variables
The following data types are applicable when variables are classified.
2.2.1 Numeric variables
Integers
An integer variable contains a whole number that has no fractional or decimal
part. The number can be positive, negative or zero. Examples of integers are
the number of students or the quantity of items in stock. Integer variables are
typically used for items that cannot be split.
Examples: 15, –2 334, 9 728
Ed 3 BPP 4th pgs.indb 5
2012/11/26 2:45 PM
6
•
BASIC PROGRAMMING PRINCIPLES
Real numbers
A real number variable contains a positive or negative number with a decimal
part. Examples of real numbers are the length of a window in metres or
centimetres, or an amount of money in Rands and cents.
Examples: 12.47, –987.123, 17.00
2.2.2 Non-numeric variables
Character
A character variable contains a single letter, number or special character, such
as $, % or @. The value of a character variable is always enclosed in quotes.
Examples: “A”, “G”, “*”, “8”
Note that the character “8”, which is declared as a character, is not regarded as
numeric and may not be used in calculations. When declared as a character, it
can be used as a code – for instance, the group number is “8”.
String
A string variable consists of two or more characters and must also be enclosed
in quotes.
Examples: “32 Long Street” or a message, such as “The name is found.”
Boolean
A Boolean value can only contain a true or false value. In an everyday life
situation a Boolean value can be compared with a light switch, which is either
on or off. In a computer language, a true value is represented by a non-zero
value, whereas a false value is represented by zero.
A Boolean variable is used to test if a specific condition is true or false, and
is also called a logical variable.
Examples: Is the person a club member? Did the student pass an exam? True
or false?
Ed 3 BPP 4th pgs.indb 6
2012/11/26 2:45 PM
GENERAL CONCEPTS AND ARITHMETIC
•
7
2.3 The value of a variable
A variable need not contain an initial value, but a value can be assigned to a
variable according to its data type – for instance, the variable called costPrice
must contain a numeric real value. A value can also be assigned to a variable
while the statements in the algorithm are being processed.
An illustration of this is the scoreboard for a football match displaying
the scores of the two teams. A team has only one score at any given time. For
example, at the beginning the score will be zero, but after the first goal it will be
one. At no time may the scoreboard contain two scores for one team.
Before the football match between Bafana Bafana and Brazil, the scoreboard
would be:
South Africa
Brazil
0
0
After Bafana Bafana score their first goal, the scoreboard would change to:
South Africa
Brazil
1
0
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.
Description
Variable name
Variable type
Possible value
Name of student
stName
String
“John Smart”
Number of books
noBooks
Integer
234
Price of item
price
Real number
78.56
Student? (Y/N)
student
Boolean
true (or 1)
Code (A – C)
code
Character
“B”
Table 4: Examples of variable names, types and values
Ed 3 BPP 4th pgs.indb 7
2012/11/26 2:45 PM
8
•
BASIC PROGRAMMING PRINCIPLES
Exercises
Complete the following table:
Description
Variable name
Variable type
Possible value
Colour of dress
Height of person in metres
Adult?
Age in years
Salary in R/c
Title of book
Player in match?
Class code (K, L or M)
Name of lecturer
Number of computers
3 Constants
All the rules of variables apply to constants as well, except that constants have
a fixed value that cannot change throughout the entire program. Constants
are used in cases where we know that the value will never vary during the
execution of the program. A constant may be any data type.
Examples:
There are always 24 hours in a day.
The value of π is always 3.14159.
A message or legend to be printed is “The name of the student is”.
4 Using variables in expressions and
assignments
The assignment symbol (=) is used to assign an initial value or an expression
to a variable.
Syntax:
Variablename = Value
or
Variablename = Expression
Example:
totalNumStudents = 20
totalNumStudents = numMales + numFemales
Ed 3 BPP 4th pgs.indb 8
2012/11/26 2:45 PM
GENERAL CONCEPTS AND ARITHMETIC
•
9
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.
5.1 Key words used in arithmetic expressions
There are a number of key words that can be used in problem statements
containing mathematical operations.
Addition
Key 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
Sum
Together, Thabu and Jabu worked for 18 hours.
Calculate the total of the first and the second sets of
quantities.
What is the sum of the prices of 3 items?
Added to
The 4th test mark must be added to the final mark.
Total of
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.
Ed 3 BPP 4th pgs.indb 9
2012/11/26 2:45 PM
10
•
BASIC PROGRAMMING PRINCIPLES
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
hours worked.
Calculate the product of the number of items and the price
per item.
The total number must be increased by a factor of 12%.
Multiplied by
Product of
By a factor of
Division
Key words
Examples
Per
Calculate the kilometres travelled per litre of fuel.
Out of
Quotient of
15 out of 60 is 25%.
If the ratio of girls to boys is 2:3 and there are 25 children,
how many girls are there?
Divide the number of minutes by 60 to get the number of
hours
The quotient of 80 and 8 is 10.
Percent
50% percent of 250 ml is 125 ml.
Ratio
Divide by
Equals
Key words
Examples
Is/are
Will be
The sum of 20 and 12 is 32.
The difference between my age and my grandmother’s
age was 60 years.
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
be replaced by the sales amount.
Was/were
Replaced by
5.2 Arithmetic expressions and equations
Equations are frequently used in arithmetic calculations, for example:
answer = 4 + 7
Ed 3 BPP 4th pgs.indb 10
2012/11/26 2:45 PM
GENERAL CONCEPTS AND ARITHMETIC
•
11
The calculation to the right of the equal sign is done first, then the result is
assigned to the variable on the left of the equal sign, which is ‘answer’ in this
case. So after the statement is executed, the variable called answer will contain
a value of 11.
The equals sign (=) has two meanings:
1. It can be used to assign a value to a variable.
total = 0
~ total is an integer variable
noOfStudents = 50
~ noOfStudents is an integer
2. It can be used to replace the value of a variable.
result = number * 2
~ result and number are both numeric
~ variables
sum = sum + points
~ sum and points are both numeric variables
The last example, sum = sum + points, will add the value of points to the value
of sum to produce a new value for sum. The previous value of sum is increased
by the value of the variable points.
If sum has a value of 200 and points has a value of 27, the right-hand side
of the equation will be 200 + 27 and the new value of sum will be 227. The
previous value of sum, which was 200, is now replaced by the new value, which
is 227.
5.3 Arithmetic operators
An operator is a symbol used within an expression or equation that tells
the computer how to process the data. This symbol joins the operands to be
processed – for instance, in the calculation 3 * 6, 3 and 6 are operands and * is
the operator.
The following operators are used to perform arithmetic operations:
Operator
^
*, /
\
mod
+,-
Description
Exponentiation
(to the power of )
Example
Result
Precedence
2^4
16
1
Multiplication and
division
Integer division
-TRUE
- -6
5*7
72 / 8
37 \ 5
FALSE
+6
35
9
7
Modulus arithmetic
Addition and
subtraction
37 mod 5
4+7
14 - 5
2
11
9
Negation
2
3
4
5
6
Table 5: Arithmetic operators and the rules of precedence
Ed 3 BPP 4th pgs.indb 11
2012/11/26 2:45 PM
12
•
BASIC PROGRAMMING PRINCIPLES
Integer division can only be done when dividing an integer value by another
integer value because it discards (drops) the decimal part and doesn’t round
the answer. Example: 49 \ 10 = 4
Modulus arithmetic is done when the user only wants to know what the
value of the remainder is when dividing. Example: 49 mod 10 = 9
The order of precedence in execution is important. When an expression is
executed, it is always done:
• from left to right and
• the operator with the highest order of precedence is done before the others.
Note that when operators with the same precedence occur in one expression,
they will be executed from left to right.
Study this example:
5 – 3 ^ 2 \ 8 + 17 mod 3 * 2
To find the answer to this expression, we need to determine which operator to
execute first. The answers in the steps that follow have been underlined.
Step 1: The exponentiation (3^2=9) is done first:
5 – 9 \ 8 + 17 mod 3 * 2
Step 2: Multiplication and division are done from left to right (3*2=6):
5 – 9 \ 8 + 17 mod 6
Step 3: Integer division (9\8=1) is done next:
5 – 1 + 17 mod 6
Step 4: Modulus arithmetic (17 mod 6=5) is done before addition or
subtraction:
5–1+5
Step 5: Lastly, addition and subtraction are done from left to right, so
subtraction is done first because the minus is to the left of the plus:
4+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.
Ed 3 BPP 4th pgs.indb 12
2012/11/26 2:45 PM
GENERAL CONCEPTS AND ARITHMETIC
•
13
Example: Calculate the value of the variable k where
k = a * b ^ (14 – c) mod 4 + 3 \ a, and where a, b and c are integer
variables with the following values:
a = 3, b = 5, c = 11
Substitute the values of the variables before calculating:
k = 3 * 5 ^ (14 – 11) mod 4 + 3 \ 3
= 3 * 5 ^ 3 mod 4 + 3 \ 3
= 3 * 125 mod 4 + 3 \ 3
= 375 mod 4 + 3 \ 3
= 375 mod 4 + 1
=3+1
=4
Note that (14 - 11) is executed before the other operations because it’s in
parentheses.
5.4 Setting up arithmetic equations
An arithmetic equation is also called an assignment statement in which
variables and/or constants are assigned to a variable on the left-hand side of
an equation. For example, a = b + c, where a must be a numeric variable that
will contain the result, and b and c must also have numerical values, but may
be constants or variables.
A computer cannot understand mathematical equations in the format that
we usually write them. We therefore need to translate the equation into a format
the computer can understand. Variables and/or constants on the right-hand side
of an equation are always separated by operands. When writing an arithmetic
equation, the mathematical rules, as given in Table 5, must be followed. An
equation contains only one variable to the left of the equation to store the result.
The following equation contains the variables X, A, B, C and D:
2(C + D)
X = A3 − 2B + ________
2
The equation can now be written in computer-related format, as follows:
X = A ^ 3 – 2 * B + (2 * (C + D)) / 2
Note how the brackets are used to execute the statements in the correct order.
Ed 3 BPP 4th pgs.indb 13
2012/11/26 2:45 PM
14
•
BASIC PROGRAMMING PRINCIPLES
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)
5.5 Examples using variables and constants
The following examples illustrate what you’ve just learnt. In each of the
examples, the arithmetic equation to solve the problem is given after the
variables and constants have been planned. Note that meaningful names were
chosen for variables and constants.
Example 1
Kevin works eight hours per day at a pay rate of R11 per hour. He has to
pay R12 taxi fare per day. How much money will he take home after a five-day
work week?
Variables (integer):
money
Constants (integers):
hours = 8
payRate = 11
transport = 12
noDays = 5
Equation:
money = (hours * payRate – transport) * noDays
The constants already contain values because these values are fixed, but the amount
earned, called money, must still be calculated so doesn’t have an initial value.
Note that we don’t include the units (the Rand sign R) in any calculation.
This also applies to other units such as metres, centimetres, grams,
kilograms and so on.
Ed 3 BPP 4th pgs.indb 14
2012/11/26 2:45 PM
GENERAL CONCEPTS AND ARITHMETIC
•
15
Example 2
Thandi has 257 items and wants to pack them in packets of 14 each. How many
full packets will she have?
Variables (integer):
fullPackets
Constant (integers):
items = 257
noInPacket = 14
Equation:
fullPackets = items \ noInPacket
To calculate how many will be left, you use the equation:
numLeft = items mod noInPacket
Example 3
Joseph earns R5.75 per hour. He works eight hours per day, but has to spend
R3.60 on bus fare each day. Determine his net income per day.
Variable (real number):
netIncome
Constants (real numbers):
tariff = 5.75
busFare = 3.6
noHours = 8
Equation:
netIncome = tariff * noHours – busFare
Example 4
Bonita bought a number of items at R15.85 each. She received a discount of
7.5%. Calculate the amount she has to pay.
Variables (integer):
(real numbers):
Constants (real numbers):
noOfItems
firstAmount, amountDue
discount = 7.5
priceOfItem = 15.85
The tilde character ( ~ ) is used in the following answer to indicate comments.
These comments are not part of the answer; they simply explain various aspects.
Possible equations
~ Assume noOfItems contains a value
firstAmount = noOfItems * priceOfItem
amountDue = firstAmount – (firstAmount * discount / 100)
~ The last statement could have been replaced by
amountDue = firstAmount * 0.925
~ The two arithmetic statements could have been replaced by
amountDue = noOfItems * priceOfItem * 0.925
Ed 3 BPP 4th pgs.indb 15
2012/11/26 2:45 PM
16
•
BASIC PROGRAMMING PRINCIPLES
Exercises
Question 1
Complete the following table:
Description
Variable name
Variable type
Possible value
Number of pencils
Average height of
person in metres
Symbol (A, G, R or T)
Employed?
Weight of bean in mg
Price of bread
Gender (M/F)
Notice on door
Number on door
Able to swim?
Question 2
Choose suitable variable names for each of the following and assign values
where provided:
2.1
The number of marbles in a container
2.2
The amount of money to pay
2.3
Are you registered?
2.4
Height of girl is 1.75 metres
2.5
Name of person
2.6
Code of item is K
2.7
Description of dog is Dachshund
2.8
Number of smarties in a box
Choose suitable names for the following constants and assign the correct values:
2.9
Seven days in a week
2.10
A notice contains the words “No Entry”
2.11
Value added tax at 14%
Question 3
Rewrite in computer-related format, then calculate the value of x in each of the
following equations:
3.1
x = a – 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
Ed 3 BPP 4th pgs.indb 16
2012/11/26 2:45 PM
GENERAL CONCEPTS AND ARITHMETIC
•
17
Question 4
Calculate the value of x in each of the following statements:
4.1
x = g – 5 + 14 mod h ^ 2, where g = 12 and h = 1
4.2
x = 27 * y \ 4 / 2 – z + 2, where y = 24 and z = 4
4.3
x = a / (b + 2 ^ 2) – 12 + c mod b – 2, where a = 96, b = 2, c = 98
4.4
x = (y – 2 * z) + y / 6 * w \ 2, where w = 10, y = 12, z = 2
4.5
x = 35 mod y – ( z * w + y / 3 ) + y * w, where w = 5, y = 24, z = 3
Question 5
Declare the necessary variables and constants and write arithmetic expressions
to solve the problems in each of the following examples. Remember to choose
valid and meaningful variable names.
5.1
Sandra bought a number of pairs of socks at R3.50 per pair. What is
the amount due?
5.2
Vusi wrote two tests and obtained marks in percentages for the tests.
Calculate her average mark.
5.3
Jimmy has some marbles and wants to give each of four children an
equal number. How many will each child receive?
5.4
Solly bought a number of items and the amount due is R245.60. He
receives a discount of 5%. Calculate the new amount due.
5.5
Determine the price to copy a set of notes when the price for copying the cover page is R1.50 and the price to copy the inner pages is 45
cents per double-sided page.
5.6
Nancy bought a number of items for R5.60 each. She receives a discount of 5% on the amount due. Add 14% sales tax and then calculate the amount due.
5.7
Tony scores points in two competitions – the first competition is
for 34 points and the second is for 125 points. Calculate the average
percentage scored in the two competitions.
5.8
Julius needs to know the total length of line in metres he has to buy
for three washing lines. The 3 lengths are available in centimetres.
5.9
Lesego has baked a batch of biscuits. She puts 15 biscuits in a packet
and Sipho receives the remaining biscuits. Write two equations: How
many packets of biscuits were packed by Lesego and how many biscuits Sipho received.
Ed 3 BPP 4th pgs.indb 17
2012/11/26 2:45 PM
18
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.
Ed 3 BPP 4th pgs.indb 18
2012/11/26 2:45 PM
UNDERSTANDING A PROBLEM AND USING A COMPUTER TO SOLVE IT
•
19
These are the steps you follow to ensure you understand a problem:
• read the problem carefully,
• understand what the problem entails, and
• only then write down the steps to solve the problem.
An everyday example would be getting to class in the morning.
Write down the steps to take from waking up in the morning until you get
to class.
The problem statement is very simple, and once you’ve read it you understand
what is being asked. However, you now need to write down the steps:
1. Wake up.
2. Get out of bed.
3. Wash.
4. Put on clothes.
5. Make something to eat.
6. Eat.
7. Pick up my bag.
8. Go to class.
These are the basic steps. You can include more steps to ensure that nothing
is left out. You can also omit some steps, such as making something to eat
because you eat later in the morning. Some steps can be swapped around – you
might wash after you’ve had breakfast. Others, however, have to be done in a
specific order – it’s not possible to go to class before waking up, getting out of
bed, or putting on clothes!
But, most important, your steps must always be in logical order!
These steps are called an algorithm, which is a set of instructions in a
specific sequence used to solve a problem.
2 Understanding the problem
When a programmer is faced with a problem to solve, the problem is read
carefully, and may be read a number of times to be very sure that the problem is
understood. Deleting all unnecessary information from the problem statement
can help you arrive at the crux of the problem. The examples below illustrate
how this is done.
Example 1
The Fresh Greengrocer store sells apples at 85 cents each, pears at 65 cents each
and oranges at 90 cents each. Tumi has R15 and wants to buy 10 apples and 5
pears. Calculate the amount due.
Ed 3 BPP 4th pgs.indb 19
2012/11/26 2:45 PM
20
•
BASIC PROGRAMMING PRINCIPLES
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.
Ed 3 BPP 4th pgs.indb 20
2012/11/26 2:45 PM
UNDERSTANDING A PROBLEM AND USING A COMPUTER TO SOLVE IT
•
21
Another essential aspect of understanding a problem statement is
understanding the individual words in the statement. This is illustrated in the
following examples.
Example 4
A mail order company sells CDs and books to customers all over the world.
Customers enter the name of a book or CD in the space provided on an online
form, and the mail order company immediately lets the customer know if
they have the item in stock and what the price is. The system also informs
the customer of the packaging and posting costs, and offers insurance on the
parcel. Lastly, the customer is informed about the dispatch date as well the
estimated arrival date of the parcel.
If the customer decides to order the item, his/her details, including name,
postal address and credit card details, must be entered on the form.
The mail order company then checks the details provided and informs
the customer within a very short time whether the transaction is approved or
rejected. If approved, the credit card is immediately debited with the amount
due.
What do they want me to do as the customer?
Order an item. How should this be done?
I need to access the web page on the Internet, ask for the specific item and
then, if I want to order the item, provide the necessary details. What do I need
to be able to do this?
I need to know if the item is available and if so, provide my details. I must
also have enough funds available in my credit card account to pay for the item
plus additional costs.
Mail order
company
Item in stock
Packaging and
posting cost
To insure the
parcel
Dispatch date
Credit card
Ed 3 BPP 4th pgs.indb 21
A company that uses a catalogue or web page to advertise and
sell items; once the customer has ordered and paid for an item, it
is posted to the customer.
The item is available for purchase
The cost of packaging the item and paying the postage. Also
called shipping costs.
The payment of an additional fee for which the company
promises to refund the customer should the parcel not reach the
customer.
The date that the item will be posted
A bank account that can be used to buy items by providing the
account details, such as the number, expiry date and security
number
2012/11/26 2:45 PM
22
•
BASIC PROGRAMMING PRINCIPLES
Check the
details
Transaction
approved
Transaction
rejected
Credit card
debited with
amount
The company will contact the bank online to ensure that the
credit card details are valid and that there are sufficient funds in
the account to cover the purchase
The transaction can be completed
The transaction cannot continue due to incorrect details or
insufficient funds
The amount will be deducted from the customer’s account and
paid into the mail order company’s account.
Table 1: Specific words used in the problem statement
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.
Employee
A person who works for Taxi Service
Increase in salary An amount of money added to the current salary
Annual salary
The amount earned per year
Total increase
The sum of all the salary increases for all employees
Current salary
The salary that is earned now
Table 2: Specific words in the problem statement
What do they want me to do?
Display the total additional cost in salaries. How should this be done?
Calculate the increase in salary for each employee, then add all these amounts
together to determine the total additional amount the company will be paying on
salaries. What do I need to be able to do this?
Get the employee number and current annual salary of every employee and
calculate the additional amount that must be added to the salary.
Description
Variable name
Data type
Employee number
empNumber
String
Salary
Salary
Real number
Increase
Increase
Real number
Total increase
totalInc
Real number
Table 3: Descriptions of data
Ed 3 BPP 4th pgs.indb 22
2012/11/26 2:45 PM
UNDERSTANDING A PROBLEM AND USING A COMPUTER TO SOLVE IT
•
23
3 Data processing
An algorithm is divided into three phases:
1. What data you have available to solve the problem,
2. How you’re going to solve the problem; what steps you’re going to take, and
3. What the required result is.
Figure 1 illustrates the phases in an algorithm schematically.
Input
Processing
Output
Data
Processing
Information
or
Figure 1: The phases in an algorithm
Both diagrams clearly indicate that the algorithm must receive data (input)
that must be processed to produce meaningful results (output or information).
In other words:
• Input is processed to produce meaningful output.
• Data is processed to produce meaningful information.
Example 6
The manager of a company asks a student to do some part-time work for
which he will be paid by the hour. The student needs to know how many hours
he has to work at what rate of pay before he can calculate the final amount he
will receive.
In this case, the input (data) to the algorithm are the hours and the hourly
rate of pay. The input (data) must be processed to give the output (information),
which is the amount the student will receive.
It is clear that the input (data) is meaningless unless it is processed, because
if the student knows how much he will receive per hour, but does not know
how many hours he will work, the pay cannot be calculated! On the other
hand, if the student works for 20 hours but the manager hasn’t told him how
much he will earn per hour, it is also meaningless.
Now it is possible to deduce the following:
• Unprocessed data is meaningless.
• Information is processed data.
• Output is processed data.
Ed 3 BPP 4th pgs.indb 23
2012/11/26 2:45 PM
24
•
BASIC PROGRAMMING PRINCIPLES
Example 7
Let’s look at Example 3 again: Calculate the sum of two numbers and display
the result on the screen:
Input:
Not available in the problem statement. The user has to supply
the numbers.
Processing:
Add the two numbers to determine the sum.
Output:
The sum as calculated in the processing phase and displayed
on the computer screen.
Note the following:
• The value of the numbers must be available before the sum can be
calculated.
• It is impossible to display the sum before it has been calculated.
From this, it is clear that the steps in an algorithm must always be written in
logical order.
4 The problem-solving approach
To summarise and formalise what we’ve discussed, the following steps must be
taken to find an excellent and efficient solution.
4.1 Analyse the problem
You will be given a specification for the problem to be solved. It is extremely
important that you understand the problem entirely before you try to solve it.
Work through the problem a number of times to make sure that you understand
what is expected of you. It is also important that you take the available input, or
data, into account, as well as the expected output, or information.
It may sometimes be necessary to ask for more information because the end
user hasn’t provided enough information to formulate a complete algorithm.
For example, a lecturer requests a class list containing student names, student
numbers and their final marks, for the subject Principles of Programming 1
with the subject code POP101A.
This seems like a reasonable request, but you don’t actually have enough
information. For instance, what format does the lecturer have in mind for this
report?
So you could ask questions such as:
• Must the report be in student number sequence or in surname sequence?
• What must the format of the name be − for instance, surname and initials
or surname and first name?
Ed 3 BPP 4th pgs.indb 24
2012/11/26 2:45 PM
UNDERSTANDING A PROBLEM AND USING A COMPUTER TO SOLVE IT
•
•
•
•
•
25
How is the final mark calculated? Is it the average of the year mark
and examination mark, or is it based on continuous evaluation? If it’s
continuous evaluation, what is the weighting of each test and assignment?
How many tests did the students write? Are all the marks available?
What must the headings look like? Must the subject name and code
appear in the headings? In what format must the date be printed?
Must the words FAIL, PASSED or PASSED WITH DISTINCTION be
printed next to the final mark?
Must the class average be printed at the end of the report?
You can see that, as the programmer, you must understand the problem
completely before you can start to develop the solution.
For complex problems, you can divide the task into smaller subtasks. This will
make the size and complexity of every task easier to understand and to handle.
4.2 Identify alternative ways to solve the problem
There are usually many ways to solve a given problem; however, some ways may
simply be more effective than others. It is important to look at the problem from
different angles and to consider different ways to solve it. For instance, if you
need to travel from Johannesburg to Cape Town, there are many ways to reach
your destination: you can travel by road, rail or air; you could go via Durban or
even London! What might some of the considerations be, such as cost and time?
Try to think of other ways of travelling from Johannesburg to Cape Town.
4.3 Select the most effective way to solve the problem
Suppose you decide to travel by road from Johannesburg to Cape Town. You
could go through Kimberley, Bloemfontein or Upington. You need to identify
the advantages and disadvantages of each route. The length of each route will
affect your choice. Perhaps one route is much shorter than the others, but there
are a lot of road works on that route, or the condition of the road is poor. These
are the types of conditions that will influence your final decision.
The same applies to computer logic. If you can write a solution in 200
steps/statements or in 20 statements, clearly the more effective solution is the
20-statement one.
4.4 List all the steps
Now you must present all the steps to solve the problem in an unambiguous
way, but not yet in the syntax of a programming language. At this stage
you’re planning how the processing must be done. Although you must plan
in a structured and unambiguous way, you mustn’t focus on a particular
programming language − your plan must be applicable to any language.
Ed 3 BPP 4th pgs.indb 25
2012/11/26 2:45 PM
26
•
BASIC PROGRAMMING PRINCIPLES
Although there are various ways to plan a solution, we will concentrate
on writing algorithms in pseudocode to specify the logic of a process. The
algorithm is the steps to solve a problem and the pseudocode is the way in
which these steps are expressed.
4.5 Evaluate the algorithm for accuracy
The next step is to check the logic in your algorithm for accuracy. This is called
desk checking. Work through the algorithm using various input values, exactly
as the computer would do, to test whether the algorithm produces the correct
output. This step is very important. Using a variety of input values will test all
possibilities. If you identify any logic errors, you can correct them at this early
stage. This will prevent problems when you start coding.
4.6 Pseudocode
Pseudocode is a way in which the algorithm steps are written so that they
can be followed easily and understood. It is mostly given in simple English.
Therefore it is not yet in a computer programming language, but it can be easily
converted into a computer language. Planning is never done in a programming
language as it may be too technical for the planning stage.
Although there is no formal standard for pseudocode, it should already be
a structured process because the programming code, which has to be derived
from it, must be precise.
Example:
Peter sells oranges, pears, guavas and apples. Last week he sold 50 apples, 100
pears, 80 oranges and some guavas. This week he sold twice as many items.
How many did he sell?
So to solve the problem:
1. Ask the question to obtain the number of guavas sold last week.
2. Get the number of guavas.
3. Calculate the total number by adding the four numbers to determine the
total number sold last week.
4. Multiply last week’s total by 2 to obtain this week’s total.
Looking closely at this example, you can deduce that the number of guavas, last
week’s total and this week’s total are the variables used to solve the problem.
The four steps taken to solve the problem are called the algorithm.
A pseudocode solution is written in one statement per line – or it can also
be defined as one task per line. However, if it’s a big task, it needs to be broken
down into several smaller tasks.
Ed 3 BPP 4th pgs.indb 26
2012/11/26 2:45 PM
UNDERSTANDING A PROBLEM AND USING A COMPUTER TO SOLVE IT
•
27
The initial pseudocode planning can be done in informal English, as can
be seen in the examples that follow. Thereafter, the algorithm can be written
in more structured pseudocode, although it will not yet be written in a
programming language.
Example:
You want to print a particular greeting to members of a forum.
Initial planning:
Obtain member status
If the member is new
Display standard new message
Else
Display message for registered members
Endif
Writing the algorithm in a more structured manner:
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
However, planning is never done in a computer language as indicated in the
next example. Technical knowledge of language-specific details should follow
only after planning the program logic in pseudocode has been completed. You
can clearly see that the structured solution in pseudocode is much easier to
follow than the program in a programming language, such as the Visual Basic
program below.
Ed 3 BPP 4th pgs.indb 27
2012/11/26 2:45 PM
28
•
BASIC PROGRAMMING PRINCIPLES
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
4.7 What does pseudocode entail?
There are six basic computer operations:
1. A computer can receive data.
• Read − from a file, database, or other source
• Enter − via the keyboard, scanner or other input device
2. A computer can produce information.
• Write − information to a file or a database for instance
• Display − information to the screen
3. A computer can perform arithmetic.
• Use actual mathematical symbols or the words for the symbol
• Add a number to a total
• Total = total + number
• +, -, *, /
• Calculate and compute are also used.
4. A computer can assign a value to a variable.
• Three different cases are identified:
• To give variables an initial value
• Initialise, set
• To assign a value as a result of processing
• ?=?
• x=5+y
• To keep information for later use
• Save, store
5. A computer can compare two pieces of information and select one of two
alternative actions.
if condition then
some action
else
alternative action
endif
Ed 3 BPP 4th pgs.indb 28
2012/11/26 2:45 PM
UNDERSTANDING A PROBLEM AND USING A COMPUTER TO SOLVE IT
•
29
6. A computer can repeat a group of actions
while condition (is true)
some action
loop
for a number of times
some action
next number
The structured format of these operations will be discussed in detail in the
chapters that follow.
4.8 Writing an algorithm
Although it’s the focus of this book, writing algorithms in pseudocode isn’t the
only way to plan a computer-related solution to a problem. For instance, you
can use flowcharts or Nassi Shneidermann diagrams (see Appendix A).
Example 8
Determine the weekly wage of an employee when the hours he has worked and
the hourly rate, are entered by the user.
Prepare the logic to solve the problem:
1. Ask: How many hours did the employee work?
2. Get the number of hours.
3. Ask: What is the hourly rate of pay?
4. Get the hourly rate of pay.
5. Wage = number of hours * hourly rate of pay.
6. Show the wage on the screen.
The structured algorithm could be:
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
Ed 3 BPP 4th pgs.indb 29
2012/11/26 2:45 PM
30
•
BASIC PROGRAMMING PRINCIPLES
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.
Ed 3 BPP 4th pgs.indb 30
2012/11/26 2:45 PM
31
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.
Ed 3 BPP 4th pgs.indb 31
2012/11/26 2:45 PM
32
•
BASIC PROGRAMMING PRINCIPLES
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.
Input
Output
Description
Type
Variable name
Name of learner
String
name
Age of learner
Integer
age
Name of learner
String
name (same as input)
Age of learner
Integer
age
Table 1: Input and output variables for Example 1
Programmers draw up what is known as an Input/Processing/Output (IPO)
chart, which enables them to do better and more comprehensive planning,
which, in turn, enables the programmer to write complete algorithms without
errors. The Input and Output columns in the IPO chart contain only the names
of variables, and the Processing column provides an overview of the steps.
Input
name
age
Processing
Prompt to read input
fields
Enter input fields
Show name and age on
screen
Output
name
age
Table 2: IPO chart for Example 1
Ed 3 BPP 4th pgs.indb 32
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
•
33
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:
Provide the name of the learner
Provide the age of the learner
The name of the learner is John
The age of the learner is 18
John
18
In this example, the input data was the name John and the age 18. However,
you can use other test data to test this algorithm.
In this book, we’re going to write algorithms in a specific way using
predetermined words.
An algorithm has the following properties:
• Every algorithm has a name that describes the function or purpose of
the algorithm. This algorithm is for Example 1 is called ShowDetails. The
name of an algorithm starts with an uppercase letter.
• The last statement or step is always end.
• The statements or instructions between the name of the algorithm and
the end are called the body of the algorithm.
• A ~ (tilde) indicates that a comment, which explains the code, will follow.
A comment can be on a separate line or can follow in the same line as an
instruction. A comment typically explains difficult code or why you’re
including a specific instruction. However, comments can contain any text
you wish to include. A comment can be included anywhere in an algorithm.
• Display means that a message or the contents of a variable are displayed
(shown) on the computer screen.
• Enter indicates that data must be entered via the keyboard.
• Calculation can also be done using equations. In the algorithm in
Example 2, the metre and centimetre variables will get new values.
Ed 3 BPP 4th pgs.indb 33
2012/11/26 2:45 PM
34
•
BASIC PROGRAMMING PRINCIPLES
When the ShowDetails algorithm is processed from beginning to end, the
following happens:
1. Words that follow the ~ sign are not executable because they’re comments
that explain what is happening or going to happen. In this case, the
purpose of the algorithm is explained.
2. The display “Provide the name of the learner” statement means that
something must be shown on the computer screen. In this case, the text
inside the quotes is displayed.
3. The enter name statement causes the computer to show a prompt on the
screen so that the user can use the keyboard to type a name. This name is
stored in the variable called name.
4. The next two statements enable the user to enter the age of a person to
store in the variable called age.
5. The display “The name of the learner is”, name statement displays the
results on the screen as follows − the words in quotes are shown exactly
as given, whereas name is a variable so its content is displayed. The
output is The name of the learner is John. We have now displayed a
constant and the content of a variable.
6. The same rules apply to the next statement, which displays The age of the
learner is 18.
7. The comments on the right-hand side indicate that the details in each
display statement must be shown on a new line on the screen.
8. Note how the body of the algorithm is indented.
Example 2
Problem
Enter the distance between two trees in kilometres. Calculate and display the
distance in metres and then calculate and display the distance in centimetres.
Planning
Description
Type
Variable name
Input
Distance in km
Integer
kilometre
Output
Distance in km
Integer
kilometre
Distance in m
Integer
metre
Distance in cm
Integer
centimetre
Table 3: Input and output variables for Example 2
Ed 3 BPP 4th pgs.indb 34
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
Input
kilometre
Processing
Prompt to read
kilometre
Enter kilometre
Output
Calculate metre
centimetre
•
35
kilometre
metre
Calculate centimetre
Display metre
Display centimetre
Table 4: IPO chart for Example 2
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
Note the indenting in the algorithm to enhance readability.
The input data to test this algorithm will be 3 kilometres.
Output:
Please provide the distance in km. 3
3 km is equivalent to 3000 m and to 300000 cm
If the last display statement is replaced by the following three display statements,
the output will change as follows:
display “Distance = ”, kilometre, “ km”
~ Display on a new line
display “Equivalent distance in cm = ”, centimetre, “ cm” ~ Display on a new line
display “Equivalent distance in metres = ”, metre, “ m”
~ Display on a new line
Ed 3 BPP 4th pgs.indb 35
2012/11/26 2:45 PM
36
•
BASIC PROGRAMMING PRINCIPLES
New output:
Please provide the distance in km. 3
Distance = 3 km
Equivalent distance in cm = 300000 cm
Equivalent distance in metres = 3000 m
2 Testing the logic of an algorithm
Even when carefully planned and written correctly, programmers can’t assume
that their algorithm is error-free and will produce the intended results in a
form that is easy to read and understand. It is very important to test this logic
for correctness and readability.
To achieve the intended results, the programmer compiles a set of test data
to test the logic, as we did in Examples 1 and 2. The test data must include a
sample of every category of correct data and incorrect data. The test data must
also be realistic. At this stage, our test data is simple, but more complicated
algorithms will need more test data to ensure that no errors will occur.
The logic can also be tested using a trace table, also known as desk
checking or a walkthrough table.
Example 3
Problem
Enter the length and the width of a tennis court in metres, then calculate
and display the perimeter and the area of the tennis court.
Planning
Input
Output
Description
Type
Variable name
Length of court
Real
length
Width of court
Real
width
Perimeter of court
Real
perim
Area of court
Real
area
Table 5: Input and output variables for Example 3
Ed 3 BPP 4th pgs.indb 36
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
Input
Processing
Output
length
Prompt for input fields
perim
width
Enter input fields
Calculate perimeter and
area
Display output fields
area
•
37
Table 6: IPO chart for Example 3
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.
Instruction
length
width
perim
area
display
enter
Please enter length
30
display
enter
calculate perim
calculate area
Output
Please enter width
10
80
300
display
display
The perimeter of
the tennis court is
80 metres
The area of the
tennis court is 300
square metres
Table 7: A trace table for the CalcTennisCourt algorithm
Ed 3 BPP 4th pgs.indb 37
2012/11/26 2:45 PM
38
•
BASIC PROGRAMMING PRINCIPLES
The instructions are listed in the left column, followed by the variables and
the output. If, for instance, an alphabetic character is entered for the length, it
will not be able to do the calculation and an error will occur.
Output:
Please enter length
30
Please enter width
10
The perimeter of the tennis court is 80 metres
The area of the tennis court is 300 square metres
Note that the algorithm can also accept and display real values. The length
could have been 30.5 and the width 10.2, which results in 81.4 metres and
311.10 square metres.
Example 4
Problem
Enter two integers on the keyboard and calculate and show the average of these
two integers on the screen.
Planning
Input
Output
Description
Type
Variable name
First number
Integer
num1
Second number
Integer
num2
Average
Real
average
Table 8: Input and output variables for Example 4
Input
Processing
Output
num1
Prompt for num1 and num2
average
num2
Enter num1 and num2
Calculate average
Show average on the screen
Table 9: IPO chart for Example 4
Ed 3 BPP 4th pgs.indb 38
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
•
39
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:
Enter first number 24
Enter second number 40
The average of the two numbers is 32
Example 5
Problem
Jason works as a part-time assistant in a bookshop and receives an hourly
wage. Enter the number of hours he worked for a specific week, as well as the
pay rate per hour. He has to pay R8 towards the recreation club. Calculate and
display how much take-home pay he’s earned for the week.
Planning
Input
Output
Description
Type
Variable name
Hours worked
Integer
hours
Rate of pay
Real
rate
Weekly wage
Real
wage
Table 10: Input and output variables for Example 5
Ed 3 BPP 4th pgs.indb 39
2012/11/26 2:45 PM
40
•
BASIC PROGRAMMING PRINCIPLES
Input
Processing
Output
hours
Prompt for input fields
wage
rate
Enter hours and rate
Calculate wage
Display wage on screen
Table 11: IPO chart for Example 5
Algorithm
CalcWeeklyWage
~ Calculate and display the weekly wage for Jason
display “Provide number of hours Jason worked”
enter hours
display “Provide rate of pay”
enter rate
~ Do calculations and display
wage = hours * rate – 8
display “Jason earned R ”, wage, “ for the week.”
end
~ Display on new line
~ Display on new line
~ Display on new line
The input data used to test this algorithm: hours worked = 24 and rate of pay
= R12.
Output:
Provide number of hours Jason worked
Provide rate of pay
Jason earned R280 for the week.
24
12
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.
Ed 3 BPP 4th pgs.indb 40
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
•
41
Planning
Description
Type
Variable name
Input
Monthly salary
Real
salary
Intermediate
Money to divide
Real
remainder
Output
Room
Real
room
Food
Real
food
Clothes
Real
clothes
Transport
Real
transport
Charity
Real
charity
Pocket money
Real
pocket
Table 12: Input and output variables for Example 6
Note that an intermediate variable can be used to assist with the calculations.
It is not part of the input or the output.
Input
Processing
Output
salary
Prompt for salary
room
Enter salary
food
Calculate various categories
clothes
Display output fields
transport
charity
pocket
Table 13: IPO chart for Example 6
Ed 3 BPP 4th pgs.indb 41
2012/11/26 2:45 PM
42
•
BASIC PROGRAMMING PRINCIPLES
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:
Provide Tebogo’s monthly salary: 2000
Tebogo divided her salary as follows:
Room
R450.00
Food
R775.00
Clothes
R310.00
Transport
R232.50
Charity
R77.50
Pocket money R155.00
Example 7
At The Friendly Store, items can be bought individually, in which case the full
amount is paid. However, customers can also buy items in bulk packages of 50
or 100, in which case a discount per item applies. There’s a 10% discount per
item on bulk packages of 50, and a 12.5% discount per item on bulk packages
of 100.
Ed 3 BPP 4th pgs.indb 42
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
•
43
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
Input
Intermediate
Output
Description
Type
Variable name
Price for one item
Discount price for one item if 50
are bought
Discount price for one item if 100
are bought
Price of bulk pack of 50 items
Real
amtOne
Real
amt50_One
Real
amt100_One
Real
amt50
Real
amt100
Real
save1
Real
save2
Real
save50
Real
save100
Price of bulk pack of 100 items
Amount saved on one item for
bulk pack of 50
Amount saved on one item for
bulk pack of 100
Total amount saved on bulk pack
of 50
Total amount saved on bulk pack
of 100
Table 14: Input and output variables for Example 7
Input
Processing
Output
amtOne
Prompt for input value
amt50
Enter amtOne
amt100
Calculate output values
save1
Display output
save2
save50
save100
Table 15: IPO chart for Example 7
Ed 3 BPP 4th pgs.indb 43
2012/11/26 2:45 PM
44
•
BASIC PROGRAMMING PRINCIPLES
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
Complete the following trace table:
Instruction amtOne
Ed 3 BPP 4th pgs.indb 44
amt50
amt100 save1 save2 amt50
amt100 save50 save100
output
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
•
45
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
Description
Type
Variable name
Input
Weight of food and plate in kg
Real
weightFoodPlateKG
Intermediate
Weight of food alone per 100 g
Real
weightFood100G
Output
Amount due
Real
amtDue
Weight of food per 100 kg
Real
weightFoodKG
Table 16: Input and output variables for Example 8
Input
Processing
Output
weightFoodPlate
Prompt for weight
amtDue
Enter the weight
WeightFoodKG
Calculate the amount due
Display the output
Table 17: IPO chart for Example 8
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
Ed 3 BPP 4th pgs.indb 45
2012/11/26 2:45 PM
46
•
BASIC PROGRAMMING PRINCIPLES
3 Calculating the outcome of an algorithm
It is often necessary to determine the exact outcome of a set of instructions in
an algorithm or program. Usually these statements include tricky calculations
so the programmer needs to ensure that the calculation has been done correctly
and must also know what result to expect. This could have been done with a
trace table, but we only need to test the calculations, not the entire algorithm, so
we can use a shorter method. We’ll study two examples to explain this method.
Study the following statements. Note the exact output that will be displayed
after these statements have been executed.
Example 9
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
After the first statement is executed, the value of A will be 3.
A
B
C
3
After the next statement the value of B will be 7.
Ed 3 BPP 4th pgs.indb 46
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
A
B
•
47
C
3
7
Now the calculation must be done to determine the new value of A.
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
Now the calculation must be done to determine the value of C.
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.
Ed 3 BPP 4th pgs.indb 47
2012/11/26 2:45 PM
48
•
BASIC PROGRAMMING PRINCIPLES
The last statement:
display “The value of C is ”, C
will first display the content of the legend followed by the value of the variable
as follows:
The value of C is 33
This will be the answer to the question because it is the only output displayed
by the algorithm. The table assisted us only in calculating the values of the
variables as the statements were executed.
Example 10
Use the same set of instructions as Example 9, but change the display statement
to
display “The value of A plus B is ”, A + B
Then the output will be:
The value of A plus B is 13
The value of A plus B (6 + 7 = 13, as can be seen in the table) will be calculated
before the result is displayed.
Example 11
Use the same instructions again, but change the display statement to show the
values of all three the variables in one line:
display “A = ”, A, “ B = ”, B, “ C = ”, C
Then the output will be:
A = 6 B = 7 C = 33
How did we insert the spaces between the three answers?
Exercises
Question 1
In each case, indicate the variables used, draw an IPO chart and write an
algorithm to solve the problem. Test your algorithm by doing a trace table for
every odd-numbered question.
Ed 3 BPP 4th pgs.indb 48
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
1.10
Ed 3 BPP 4th pgs.indb 49
•
49
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.
Enter two integers. Calculate and show the sum, difference and
product of these two integers on the screen.
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.
Enter Ridwaan’s height in metres and centimetres. Calculate and
display his height only in centimetres (1 metre = 100 centimetres).
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.
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.
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.
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.
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.
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.
2012/11/26 2:45 PM
50
•
BASIC PROGRAMMING PRINCIPLES
1.11
1.12
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.
Henry rents a trailer to move stock to a store. The basic cost is R200
per day. He also pays a specific amount per kilometre travelled,
entered by the owner. The owner also has to enter the kilometres
and the number of days that Henry rented the trailer. Determine and
show the amount due on the screen.
Question 2
Study the following variables with their initial values, and the statements that
follow, which are based on the variables and their initial values. Display the
exact output that will be displayed after the statements have been executed.
Description
Data type
Variable name
Initial value
Gross monthly salary
Real
salary
R15234.50
Tax payable
Real
tax
Net monthly salary
Real
netSal
Percentage tax payable
Integer
taxPerc
32
Statements
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
display “B = ”, B
display “C = ”, C
end
Ed 3 BPP 4th pgs.indb 50
~ On new line
~ On new line
~ On new line
2012/11/26 2:45 PM
WRITE ALGORITHMS IN SEQUENTIAL STEPS
•
51
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
display “The value of C = ”, C
end
~ On new line
~ On new line
3.4
FourthCalculation
X = 15
Y = 23
Z=2
Y=X*Z\7
W = X mod 8
display “The value of Y is ”, Y
display “The value of W is ”, W
end
~ On new line
~ On new line
3.5
FifthCalculation
k = 12
m = 30
x = (k – 8) ^ 3 + m * 4 / (k – 6)
m=m+2
k = k – 20
display “x = ”, x
display “m = ”, m
display “k = ”, k
end
Ed 3 BPP 4th pgs.indb 51
~ On a new line
~ On a new line
~ On a new line
2012/11/26 2:45 PM
52
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.
Ed 3 BPP 4th pgs.indb 52
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
53
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
Pseudocode symbol
Description
Example
=
Equal to
A=5
<
Less than
number < 97
>
Greater than
totalAmount > 100
<=
Less than or equal to
noStudents <= 50
>=
Greater than or equal to
weight >= 75
<>
Not equal to
quantity <> 17
Table 1: The operators used in relational comparisons
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:
1. b <= a - 3 where b = 5 and a = 7
Substitute:
5 <= 7 - 3
Answer to calculation:
5 <= 4
Outcome of relational comparison:
false
2. m + 7 > n - 3 * p where m = 4, n = 12 and p = 5
Substitute:
4 + 7 > 12 - 3 * 5
Answer to first calculation: (* has higher priority than +)
4 + 7 > 12 - 15
Answer to second calculation: (from left to right)
11 > 12 - 15
Answer to third calculation:
11 > -3
Outcome of relational comparison:
true
Ed 3 BPP 4th pgs.indb 53
2012/11/26 2:45 PM
54
•
BASIC PROGRAMMING PRINCIPLES
Exercises
Evaluate the following expressions:
1. a + t <> (a + b) * 4
2. k ^ 2 <= m mod 5 + 29 – n
3. (x \ 8 –2) + 3 > y / 12 mod 2
4. d + 4 * g / 2 < g * 3 + 14
where a = 4, b = 17 and t = 20
where k = 5, m = 63, n = 7
where x = 59, y = 96
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
symbol
Description
NOT
Yields the opposite
AND
Both expressions
must be True to
yield True
OR
Only one expression
must be True to
yield True
Example
Result
NOT True
NOT False
True AND True
True AND False
False AND True
False AND False
True OR True
True OR False
False OR True
False OR False
False
True
True
False
False
False
True
True
True
False
Precedence
1
2
3
Table 2: The operators used in logical operations
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
Ed 3 BPP 4th pgs.indb 54
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
•
•
•
55
NOT
AND
OR
When different operators are combined in one expression, all the mathematical
operators will be processed first, then the relational operators, and finally the
logical operators.
However, the order can be changed using parentheses. For example, if an
OR must be processed before an AND, parentheses can be inserted.
Example:
Let A, B, C and X be Boolean variable with the following values:
A = True, B = False and C = True
Evaluate the equation:
X = A OR B AND C
Substitute:
X = True OR False AND True
AND is done first:
X = True OR FALSE
= False
Use parentheses:
X = (A OR B) AND C
= (True OR False) AND True
= True AND True
= True
Tables 3, 4 and 5 illustrate the order of precedence of all operators.
Operator
^
*/
\
mod
+-
Description
Exponentiation
(to the power of )
Negation
Multiplication and
division
Integer division
Modulus arithmetic
Addition and
subtraction
Example
Result
Precedence
2^4
16
1
-True
--6
5*7
72 / 8
37 \ 5
37 mod 5
4+7
14 - 5
False
+6
35
9
7
2
11
9
2
3
4
5
Table 3: Highest priority, from left to right
Ed 3 BPP 4th pgs.indb 55
2012/11/26 2:45 PM
56
•
BASIC PROGRAMMING PRINCIPLES
Operator
Description
Example
=
Equal to
A=5
<
Less than
number < 97
>
Greater than
totalAmount > 100
<=
Less than or equal to
noStudents <= 50
>=
Greater than or equal to
weight >= 75
<>
Not equal to
quantity <> 17
Table 4: Second highest priority, from left to right
Operator
Description
NOT
Yields the opposite
AND
Both expressions must
be TRUE to yield True
OR
Only one expression
must be TRUE to yield
True
Example
NOT True
NOT False
True AND True
True AND False
False AND True
False AND False
True OR True
True OR False
False OR True
False OR False
Result
False
True
True
False
False
False
True
True
True
False
Precedence
1
2
3
Table 5: Lowest priority, from left to right
Examples
Evaluate the following expressions:
1. D OR K AND NOT S
where D = TRUE, K = FALSE, S = TRUE
Substitute:
TRUE OR FALSE AND NOT TRUE
TRUE OR FALSE AND FALSE
TRUE OR FALSE
TRUE
2. M > 7 AND D < S ^ 2
Substitute:
7 > 7 AND 8 < 4 ^ 2
7 > 7 AND 8 < 16
FALSE AND 8 < 16
FALSE AND TRUE
FALSE
Ed 3 BPP 4th pgs.indb 56
where M = 7, D = 8, S = 4
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
3. D < (E + 7) AND G OR (A * C) >= (D – E + C)
A = 5, C = 12, D = -15, E = -17, G = FALSE
•
57
where
Substitute:
-15 < (-17 + 7) AND FALSE OR (5 * 12) >= (-15 – -17 + 12)
-15 < (-17 + 7) AND FALSE OR (5 * 12) >= (-15 + 17 + 12)
-15 < -10 AND FALSE OR (5 * 12) >= (-15 + 17 + 12)
-15 < -10 AND FALSE OR 60 >= (-15 + 17 + 12)
-15 < -10 AND FALSE OR 60 >= (2 + 12)
-15 < -10 AND FALSE OR 60 >= 14
TRUE AND FALSE OR 60 >= 14
TRUE AND FALSE OR TRUE
FALSE OR TRUE
TRUE
Exercises
Evaluate the following expressions where A = 5, B = 7, C = 12, D = -4, E =
TRUE and F = FALSE:
1 A * 3 >= B – 14 \ 3 AND F OR C <= D + 3
2 NOT F OR E AND D + C = A
3 (C – D) * 2 <> A + B OR E AND F OR B > D + B ^ 2
4 D = C MOD 5 AND NOT F OR NOT (A + D <= A – D)
3 The simple If statement
If statements are also called if-then statements because they cause the computer
to test a condition before executing the ‘then’ part of the statement. If the
condition is true, the ‘then’ part is executed. If not, the if statement is skipped
entirely and the computer continues executing the rest of the program.
If statements are best explained using an example:
If an employee has worked more than 45 hours during the past week, a bonus
of R300 must be added to his or her wages.
Pseudocode
~ Test if the employee worked overtime
if hours > 45 then
wage = wage + 300
endif
Ed 3 BPP 4th pgs.indb 57
~ Executed only if the condition is true
2012/11/26 2:45 PM
58
•
BASIC PROGRAMMING PRINCIPLES
Explanation of the above three lines:
if hours > 45 then
~ This statement tests if the hours worked exceed 45.
wage = wage + 300
~ If the test is true (the employee has worked more than 45 hours),
~ the previous value in the wage variable is replaced by an increased
~ wage of R300 more.
endif
~ This line ends the if structure and the execution of statements will
~ continue after the endif statement, regardless of the outcome of
~ the if test.
If the employee has not worked more than 45 hours, the execution of statements
will continue after the endif key word. In other words, the statement to increase
the wage is skipped.
If statement syntax
if condition then
statement(s)
endif
Example
if mark >= 50 then
display “Student has passed”
endif
This algorithm can also be represented as a flowchart.
No
Condition?
Yes
Statement(s)
No
Mark > 50?
Yes
Student has
passed
Figure 1: Flowchart of a simple If statement
Ed 3 BPP 4th pgs.indb 58
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
59
Notes
• There can be any number of statements in the body of an if statement −
between if and endif.
• The statements in the body of an if statement execute only if the
condition is TRUE.
• Statements within an if statement are always indented to aid the
readability of the algorithm.
• If and endif are written in the same column, whereas the body of the if
statement is indented.
• An if statement always yields a Boolean value, so the result is always
TRUE or FALSE.
It is also possible to test whether a specific condition is not true by inserting
the word NOT before the condition.
if NOT condition then
statement 1
statement 2
statement 3
statement n
endif
Example:
if mark NOT < 50 then
display “Student has passed”
endif
3.1 Testing a program that has an If statement
Study the following program:
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.
Ed 3 BPP 4th pgs.indb 59
2012/11/26 2:45 PM
60
•
BASIC PROGRAMMING PRINCIPLES
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.
Description
Type
Variable name
Input
Cost of cake
Real
expense
Intermediate
Cake selling price
Real
cakePrice
Price per slice
Integer
slicePriceInteger
Price per slice
Real
slicePriceDecimal
Price of slice
Integer
slicePriceInteger
Output
Table 6: Input and output variables for CalcCakePrice algorithm
Input
Processing
Output
expense
Prompt for expense
slicePriceInteger
Enter expense
Calculate
slicePriceInteger
Display slicePriceInteger
Table 7: IPO chart for CalcCakePrice algorithm
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
Ed 3 BPP 4th pgs.indb 60
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
61
Test the program using a manual calculation
Use as test data:
Expense
R18.60
Increase by 30%
R24.18
Gross price per slice
R2.418
Integer division results in R2 per slice of cake
Because there is a 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.
Instruction
expense
cakePrice
slicePriceInteger
slicePriceDecimal
outcome
of if
Provide
the cost
of the
cake
display
enter
calculate
calculate
18.60
24.18
2
calculate
2.418
if
calculate
output
True
3
display
The price
of a slice
of cake
is R3
Table 8: The inclusion of an If statement in a trace table
The instruction is listed in the leftmost column, followed by the variables, the
outcome of the if statement, and finally the output, as shown in Table 8.
Output:
Provide the price of the cake 18.60
The price of a slice of cake is R3
Whenever there’s an if statement in an algorithm, you should prepare test data
that tests whether all possible outcomes of the if statement work correctly.
Ed 3 BPP 4th pgs.indb 61
2012/11/26 2:45 PM
62
•
BASIC PROGRAMMING PRINCIPLES
3.2 Examples of simple If statements
In this section we’ll discuss the planning of various problems that can be solved
using simple if statements.
Example 1
Problem
John wishes to buy a number of pencils at a given price. The seller must enter
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
Input
Output
Description
Type
Variable name
Number of pencils
Integer
number
Price of one pencil
Real
price
Amount due
Real
amount
Table 9: Input and output variables for Example 1
Input
number
price
Processing
Prompt to read input
values
Enter input values
Output
amount
Calculate amount
Display amount
Table 10: IPO chart for Example 1
Ed 3 BPP 4th pgs.indb 62
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
63
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
Test the program twice using:
number = 16, price = R3.50 (fewer than 25 pencils)
number = 30, price = R2.25 (equal to or more than 25 pencils)
Output:
Provide the number of pencils bought 16
Provide price of one pencil 3.50
The amount due is R56
Provide the number of pencils bought 30
Provide price of one pencil 2.25
The amount due is R62.44
Ed 3 BPP 4th pgs.indb 63
2012/11/26 2:45 PM
64
•
BASIC PROGRAMMING PRINCIPLES
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
Description
Type
Variable name
Input
Mark obtained
Integer
mark
Output
Mark obtained
Integer
mark
Message
String
message
Table 11: Input and output variables for Example 2
Input
Processing
Output
mark
Prompt to read mark
mark
price
Enter mark
Test mark to determine
message
Display output fields
message
Table 12: IPO chart for Example 2
Algorithm
PrepareResult
~ Prepare and display student result
display “Provide mark obtained ”
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
end
~ Display on new line
~ Display on new line
Test the program twice with marks of 45 and 69 respectively.
Ed 3 BPP 4th pgs.indb 64
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
65
Output:
Provide mark obtained 45
The mark is 45. Result = fail
Provide mark obtained 69
The mark is 69. Result = pass
Note that the message was initially set to “pass” and then tested. If the mark
was not equal to or more than 50, the message was changed to “fail”.
Exercises
Do the planning and write an algorithm to solve the following problems.
Prepare test data for the examples to test all possibilities, and draw a trace table
for each.
1. Henry rents a trailer to move his furniture to his new house. The basic
cost is R200 per day plus a specific amount that must be entered by him
per kilometre travelled. He also has to enter the distance in kilometres.
If Henry travelled less than 50 kilometres, an additional surcharge of 5%
is payable on the amount due for the distance. However, if he used the
trailer for more than 400 kilometres, he receives a discount of 12% on the
amount due for the distance. Calculate and display the amount due. Hint:
Use two different if statements in your algorithm.
2. Jessie and Sally want to buy a large pizza to share. Enter the cost of the
pizza and the amounts that Jessie and Sally each have in their purses. If
they have enough money, display a message that indicates that they can
buy the large pizza. However, if they don’t have enough money, display a
message saying that they have to buy a small pizza.
3. Harry earns R16.50 per hour. If he works more than 40 hours, he receives
an extra R10 per hour. The employer enters the number of hours Harry
has worked. Calculate and display Harry’s total wages.
4. Dumisane works at a company where all the employees receive a bonus
of R500, except the employees in Department 7, who receive a bonus of
R550. Enter his gross salary and his department number. Calculate the
gross (total) income. Subtract 20% of the gross income for tax. Determine
and display Dumisane’s net income on the screen.
Ed 3 BPP 4th pgs.indb 65
2012/11/26 2:45 PM
66
•
BASIC PROGRAMMING PRINCIPLES
4 The If-then-else statement
We’ve tested a specific condition and, if the condition proved to be TRUE,
we processed certain statements. It is, however, possible to process other
statements when the condition is not TRUE, but FALSE.
Suppose all the employees in a company receive an increase of 8%, but the
employees in Department A, which performed the best, receive an increase of
10%. This can be accomplished by means of an if statement that contains an
else clause, as shown in the following example.
if dept = “A” then
increase = salary * 0.1
else
increase = salary * 0.08
endif
salary = salary + increase
Yes
~ Executed if the condition is true
~ Executed if the condition is false
dept = “A”?
increase = salary*
0.1
No
increase = salary*
0.08
salary = salary +
increase
Figure 2: Flowchart of an If-then-else statement
Ed 3 BPP 4th pgs.indb 66
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
67
4.1 Examples of If-then-else statements
In this section, we’ll discuss the planning of various problems that can be
solved using if-then-else statements.
Example 3
Problem
Angelina and Freedom are taking part in the final round of a competition.
One rule of the competition is that judges may not assign equal points to
competitors at this stage. Enter the number of points that each competitor
obtains. Compare the points and determine who the winner is. Display the
winner’s name and number of points on the screen.
Planning
Input
Output
Description
Type
Variable name
Angelina’s points
Integer
pointA
Freedom’s points
Integer
pointF
Winner’s points
Integer
pointW
Winner’s name
String
winner
Table 13: Input and output variables for Example 3
Input
Processing
Output
pointA
Prompt for points
winner
pointF
Enter points
pointW
Determine winner
Display winner and
points
Table 14: IPO chart for Example 3
Ed 3 BPP 4th pgs.indb 67
2012/11/26 2:45 PM
68
•
BASIC PROGRAMMING PRINCIPLES
Algorithm
DetermineWinner
~ Determine the winner of the competition
display “Provide points for Angelina”
enter pointA
display “Provide points for Freedom”
enter pointF
~ Find the winner
if pointA > pointF then
pointW = pointA
winner = “Angelina”
else
pointW = pointF
winner = “Freedom”
endif
~ Display result
display “The winner is ” , winner
display “ and the winning points are: ” , pointW
end
~ Display on new line
~ Display on new line
~ More than one statement in body of if
~ Display on new line
Test the program
Angelina obtained 175 points and Freedom obtained 179 points.
Output:
Provide points for Angelina 175
Provide points for Freedom 179
The winner is Freedom and the winning points are: 179
Example 4
Problem
Dennis loves reading books and you have been asked to calculate how many
days he will need to read a given book, by writing an algorithm to solve the
problem. Enter the number of pages in the book and the number of pages that
he is able to read per day. Calculate and display how long it takes to read the
book. You also need to determine whether it is possible for him to read five
books with the same number of pages during his 14 days of holiday. Display
the answer.
Ed 3 BPP 4th pgs.indb 68
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
69
Planning
Description
Type
Variable name
Pages per book
Integer
bookPages
Pages per day
Integer
dayPages
Intermediate
Days to read 5 books
Real
days
Output
Days per book
Real
bookDays
Message
String
message
Input
Table 15: Input and output variables for Example 4
Input
Processing
Output
bookPages
Prompt for input values
bookDays
dayPages
Enter input values
message
Calculate bookDays
Determine message
Display output values
Table 16: IPO chart for Example 4
Algorithm
ReadingSpeed
display “Provide number of pages per book ”
enter bookPages
display “Provide number of pages Dennis can read per day ”
enter dayPages
~ Calculate days per book
bookDays = bookPages / dayPages
~ Determine days to read 5 books
days = bookDays * 5
~ Display on new line
~ Display on new line
~ An intermediate
~ variable is used
~ On a new line
display “Dennis takes ”, bookDays, “ days per book ”
~ 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
Ed 3 BPP 4th pgs.indb 69
2012/11/26 2:45 PM
70
•
BASIC PROGRAMMING PRINCIPLES
Test the program
Book has 120 pages
Dennis can read 50 pages per day
Output;
Provide number of pages per book 120
Provide pages read per day 50
Dennis takes 2.4 days per book
Dennis can read five books during the holidays.
Exercises
1. In each of the following cases, do the planning and write an algorithm to
solve the problem:
1.1 The Great College offers two different courses in Programming that
are offered as self-study courses in which the lecturer assists. The
student can decide beforehand how many weeks he or she wants to
study. The code of the first course is A, and the code for the second is
B. You may assume that the user will only enter an A or a B. The price
for course code A is R234 per week, whereas the price for the other
course is R287.50 per week. The student has to enter the course code
and the number of weeks of study. Calculate the total price of the
course and display the course code and total price on the screen.
1.2 Spectators can purchase tickets to attend a soccer match at R15 per
ticket. Anyone who buys eight or more tickets pays only R12.50 per
ticket. Prompt the user to enter the number of tickets bought, then
calculate and display the amount due.
2. Describe the variables and write only the if statement for the following.
You may choose your own variable names if they haven’t been specified.
2.1 The weights of two dogs, Fluffy and Terry, are available. Display the
name of the dog that weighs more than the other dog.
2.2 An employee’s salary, called empSalary, has been entered. Determine
and display a message to indicate whether this person needs to pay
income tax. Only people with an income of more than R3 000 per
month have to pay tax.
2.3 Tom decided that he must have one shirt for every pair of pants.
Determine whether this is true and display an appropriate message.
2.4 Josie wants to go to the movies, but isn’t allowed to go unless she’s
done her homework – use a Boolean variable for this – and has R10
to pay for the ticket. Display a message to indicate whether she can
go.
2.5 Test a student’s mark. If the mark is more than 47, increase the mark
by 2.5%, otherwise decrease the mark by 5.7%. Display the new mark.
Ed 3 BPP 4th pgs.indb 70
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
71
3. Study the following code:
C = A * B + 3 mod 7
if A > C then
display “A has a higher value than C”
B=A–C
else
display “A is equal to or less than C”
B=C–A
endif
display “The value of B is now ”, B
display “The value of C is now ”, C
~ Display on a new line
~ Display on a new line
~ Display on a new line
~ 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.
if age >= 18 AND licensed then
display “You may drive a car.”
else
display “You may not drive a car.”
endif
Ed 3 BPP 4th pgs.indb 71
~ Licensed is a Boolean variable
2012/11/26 2:45 PM
72
•
BASIC PROGRAMMING PRINCIPLES
No
“You may not
drive a car.”
Yes
Age > =
18?
No
“You may not
drive a car.”
licensed?
Yes
“You may
drive a car.”
Figure 3: An AND compound If statement represented as a flowchart
The result of this compound test is true only when both the conditions are
true. If one or neither of the conditions is true, the result is false.
Example
If an employee is a Grade C employee or has worked for the company for more
than five years, a special bonus of R1 000.00 is awarded to the employee.
if grade = “C” OR years > 5 then
bonus = 1000
else
bonus = 0
endif
Ed 3 BPP 4th pgs.indb 72
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
No
No
Bonus = 0
Years > 5?
Grade = “C”?
Yes
•
73
Yes
Bonus = 1000
Bonus = 1000
Figure 4: An OR compound If statement represented as a flowchart
For the result of this compound test to be true, at least one of the conditions
must be true. If neither is true, the result is false.
In cases like this, where the if statement contains more than two conditions,
it is advisable to use parentheses to indicate the order in which the tests must
be done, since the tests in the parentheses are done first.
if gender = “M” OR (age > 20 AND member) then
statement(s)
endif
Or, depending on the question/conditions:
if (gender = “M” OR age > 20) AND member then
statement(s)
endif
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.
Ed 3 BPP 4th pgs.indb 73
2012/11/26 2:45 PM
74
•
BASIC PROGRAMMING PRINCIPLES
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
Input
Output
Description
Type
Variable name
Entrance fee
Real
fee
Person’s age
Integer
age
Actual fee
Real
actFee
Table 17: Input and output variables for Example 5
Input
fee
age
Processing
Prompt to read fee and
age
Enter input values
Output
actFee
Determine actFee
Display actFee
Table 18: IPO chart for Example 5
Ed 3 BPP 4th pgs.indb 74
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
75
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
Test the program
Test the program twice:
Fee of R50 and an age of 9 years
Fee of R80.50 and an age of 32 years
Output:
Enter the normal fee 50
Enter the age in years only 9
This person must pay an entrance fee of R37.50
Enter the normal fee 80.50
Enter the age in years only 32
This person must pay an entrance fee of R80.50
Exercise
Write pseudocode for the following:
Values for the variables A and B are given. Both variables contain real
numeric values. If the value of A is greater than 17 and less than 47, swap the
values of A and B, but if the value of A is either 5 or 87, increase the value of A
by 20 and decrease the value of B by 5.
Hint: Make use of a intermediate variable if it is necessary to swap the
values.
Ed 3 BPP 4th pgs.indb 75
2012/11/26 2:45 PM
76
•
BASIC PROGRAMMING PRINCIPLES
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
Input
Output
Description
Type
Variable name
Membership status
Boolean
member
Student name
String
stName
Student name
String
stName
Message
String
message
Table 19: Input and output variables for Example 6
Input
stName
age
Processing
Prompt to read input
values
Enter input values
Output
stName
message
Prepare message
Display output values
Table 20: IPO chart for Example 6
Ed 3 BPP 4th pgs.indb 76
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
77
Algorithm
DetermineEntranceFee
display “Enter student name: ”
enter stName
display “Indicate if the student is a member or not: ”
enter member
~ Test membership
if member then
message = “ you must pay R8 entrance fee.”
else
message = “ you must pay R12 entrance fee.”
endif
~ Display results
display stName, message
end
~ Display on new line
~ Display on new line
~ Equivalent to if member = TRUE
~ Display on new line
Test the program by setting the member to TRUE after entering the name Sally
Jones. Test the program again by setting the member to FALSE after entering
the name Billy Ceronio.
Output:
Enter student name: Sally Jones
Indicate if the student is a member or not: TRUE
Sally Jones, you must pay R8 entrance fee.
Enter student name: Billy Ceronio
Indicate if the student is a member or not: FALSE
Billy Ceronio you must pay R12 entrance fee
6 Data validation
It is a good programming technique to code defensively, which means that you
try to detect and identify all errors that a user could possibly make. Users are
often inexperienced so many computer errors are actually a result of incorrect
user input. If a program can detect an error before processing, the information
will be accurate and reliable.
There are a number of data validation tests that a programmer can use to
code defensively. At this point, we’ll only test whether a numeric field contains
a numeric value before it can be used for processing. In other words, the
program will not be able to do calculations if the variable does not contain a
numeric value.
Ed 3 BPP 4th pgs.indb 77
2012/11/26 2:45 PM
78
•
BASIC PROGRAMMING PRINCIPLES
Example of a numeric test
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.
Ed 3 BPP 4th pgs.indb 78
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 1
•
79
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
else
x=y-3
display “The value of x = ”, x
endif
w = x + y * 0.5
display x, “ ”, y, “ ”, w
~ Display on a new line
~ Display on a new line
~ Display on a new line
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
Ed 3 BPP 4th pgs.indb 79
2012/11/26 2:45 PM
80
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
else
statement2
endif
Ed 3 BPP 4th pgs.indb 80
~ Process when condition is true
~ Process when condition is false
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
81
Statement1 and/or statement2 could also be if-then-else statements, depending
on the problem statement, which would change the general format to a nested
if statement, as follows:
if condition1 then
if condition2 then
statement1
else
statement2
endif
else
if condition3 then
statement3
else
statement4
endif
endif
⎫
⎪
⎬
⎪
⎭
~ If condition1 is true
⎫
⎪
⎬
⎪
⎭
~ If condition1 is false
Note the indentation in the nested if statement.
False
False
Condition 3?
Statement4
Ed 3 BPP 4th pgs.indb 81
Condition 1?
True
Statement3
True
False
Condition 2?
Statement2
True
Statement1
2012/11/26 2:45 PM
82
•
BASIC PROGRAMMING PRINCIPLES
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).
if gender = “M” then
if age > 15 then
points = 17
else
points = 20
endif
else
if gender = “F” then
if age < 18 then
points = 18
else
points = 21
endif
else
display “Invalid gender”
endif
endif
~ Code defensively and test for possible input errors
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.
Ed 3 BPP 4th pgs.indb 82
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
False
False
Gender =
“F”?
False
“Invalid
gender”
Age < 18?
Points = 21
Ed 3 BPP 4th pgs.indb 83
Age > 15?
Points = 20
False
83
True
Gender =
“M”?
True
•
True
Points = 17
True
Points = 18
2012/11/26 2:45 PM
84
•
BASIC PROGRAMMING PRINCIPLES
Example 2
Table 1 contains the values of the real variables A and B and the steps to take
when different conditions apply.
Value of A
Value of B
5.2
Greater than 20
5.2
Less than or equal to 20
6
Any value
Steps to take
Increase the value of A
by 5
Decrease the value of B
by 3.5
Initialise the values of A
and B
Table 1: Correspondences between A and B
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
endif
else
if A = 6 then
A=0
B=0
endif
endif
~ The value of A is still 5.2
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
Assign
5.2
25
Outcome of if
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.
Ed 3 BPP 4th pgs.indb 84
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
85
Now let’s test the algorithm with A = 5.2 and B = 15 as test data.
Instruction
A
B
Assign
5.2
15
Outcome of if
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
Assign
6
100
Outcome of if
If A = 5.2
False
If A > 6
True
Assign
0
Assign
0
Table 4: Test 3
In Test 3, the value for A and B both changed to 0.
Finally, let’s test the algorithm with A = 8.3 and B = 21 as test data.
Instruction
A
B
Assign
8.3
21
Outcome of if
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.
Ed 3 BPP 4th pgs.indb 85
2012/11/26 2:45 PM
86
•
BASIC PROGRAMMING PRINCIPLES
Example 3
The variables A, B, K and Z are integers.
Value of A
Value of B
Steps to take
0 - 14
0 -12
15 - 21
0 -12
22 - 40
13 or more
Double the value of K
Swap the values of A
and B
Decrease the value of
K by 5
Table 6: Conditions to be met in order to take action
if B < 13 then
if A < 15 then
K=K*2
else
if A < 22 then
Z=A
A=B
B=Z
endif
endif
else
if A >= 22 then
if A <= 40
K=K-5
endif
endif
endif
~ B is tested before A
~ B is still in the range 0 - 12 and A is >= 15
~ Z is used as an intermediate variable
~ In the else part, B will be ≥ 13
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.
Ed 3 BPP 4th pgs.indb 86
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
87
1.1 Nested If statements in programs
Example 4
The Bright Light Company is increasing the salaries of its employees according
to which department they work in, as shown in Table 7.
Department code
Percentage increase
A
7.2
B
6.8
All others
6.3
Table 7: Percentage increases by department
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
Input
Output
Description
Type
Variable name
Department code
Character
deptCode
Annual salary
New monthly
salary
Real
anSalary
Real
monSalary
Table 8: Input and output variables for Example 4
Input
deptCode
anSalary
Processing
Prompt to read input
values
Enter input values
Calculate monthly
salary
Display monSalary
Output
monSalary
Table 9: IPO chart for Example 4
Ed 3 BPP 4th pgs.indb 87
2012/11/26 2:45 PM
88
•
BASIC PROGRAMMING PRINCIPLES
Algorithm
CalcNewMonSalary
~ Calculate the increased monthly salary
~ Enter input
display “Provide the department code: ”
enter deptCode
display “Provide annual salary: ”
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
else
display “The annual salary must be numeric.”
endif
end
~ Display on new line
~ Display on new line
~ Display on new line
~ Display on new line
Test the program four times, to cover every outcome of the if statement:
Department code = A
Annual salary = R24000
Department code = B
Annual salary = R38500
Department code = G
Annual salary = R30000
Department code = C
Annual salary = R5OOOO
When testing the algorithm, we have to include incorrect data as well. In the
last example, Os instead of zeros will cause an error.
Output:
Provide the department code: A
Provide annual salary: 24000
The increased monthly salary is R2144.00
Provide the department code: B
Provide annual salary: 38500
The increased monthly salary is R3426.50
Ed 3 BPP 4th pgs.indb 88
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
89
Provide the department code: G
Provide annual salary: 30000
The increased monthly salary is R2657.50
Provide the department code: C
Provide annual salary: 5OOOO
The annual salary must be numeric.
Example 5
A vet prescribes medicine for dogs to keep them healthy and strong. The daily
dosage depends on the weight of the dog and is calculated according to the
following table:
Weight of dog in kg
Millilitres per 500 g
<5
1.0
5–8
0.9
> 8 – 12
0.75
> 12
0.6
Table 10: Dosage per weight
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
Input
Intermediate
Output
Description
Type
Variable name
Name of dog
String
name
Weight of dog
Variable used to
test/calc
Real
dogWeight
Real
number500
Name of dog
String
name
Daily medicine
Real
medicine
Table 11: Input and output variables for Example 5
Ed 3 BPP 4th pgs.indb 89
2012/11/26 2:45 PM
90
•
BASIC PROGRAMMING PRINCIPLES
Input
Processing
Output
name
Prompt for input values
name
dogWeight
Enter input values
medicine
Calculate dosage
Display name, medicine
Table 12: IPO chart for Example 5
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
Ed 3 BPP 4th pgs.indb 90
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
91
Comment 1
Each of the if statements tested only one condition, for example, the second if
statement:
if weight <= 8 then
It didn’t test if weight >= 5 AND weight <= 8, because weight was already
compared to 5 in the first if statement. When control is passed to the else part
of that if statement, the weight is definitely greater or equal to 5!
Comment 2
Similarly, it’s not necessary to test if weight > 8 AND weight <= 12. In the
last inner if statement it’s only necessary to test if weight <= 12 because it will
already be greater than 8 when it reaches this part of the if statement.
When testing this program, it’s important to use test data that tests all the
borderline cases to ensure that the program produces correct output in all
cases. It’s also necessary to test the program with incorrect input data to check
that appropriate error messages are displayed.
Test the program as follows:
Name of dog: Any name
Test weights:
3.5, 5, 8, 12 and 25.5 kg
Then test the program with weights 1O (O instead of 0) and 10.8.
Finally test the program by omitting the dog’s name.
Output:
Provide the name of the dog: Fluffy
Provide the weight of dog in kg (to nearest 500 g): 3.5
Fluffy must receive a daily dose of 7.0 ml
Provide the name of the dog: Daisy
Provide the weight of dog in kg (to nearest 500 g): 5
Daisy must receive a daily dose of 9.0 ml
Provide the name for the dog: Georgy Girl
Provide the weight of dog in kg (to nearest 500 g): 8
Georgy Girl must receive a daily dose of 14.4 ml
Provide the name for the dog: Danny Boy
Provide the weight of dog in kg (to nearest 500 g): 12
Danny Boy must receive a daily dose of 18.0 ml
Ed 3 BPP 4th pgs.indb 91
2012/11/26 2:45 PM
92
•
BASIC PROGRAMMING PRINCIPLES
Provide the name for the dog: Victor
Provide the weight of dog in kg (to nearest 500 g): 25.5
Victor must receive a daily dose of 30.6 ml
Provide the name for the dog: Lady
Provide the weight of dog in kg (to nearest 500 g): 1O
The weight entered for Lady must be numeric.
Provide the name for the dog: Tinky
Provide the weight of dog in kg (to nearest 500 g): 3.8
The weight must be in kg and to the nearest 500 g, e.g. 3, 3.5 or 4.
Provide the name for the dog:
The name of the dog must be entered
Example 6
The price of hiring a car per day from the Reliable Car Hire Company depends
on the type of car the customer hires. The customer may choose between small
(S), medium (M) and large (L) cars as shown in Table 13.
Size of car
Daily price in Rand
S
200
M
260
L
400
Table 13: Car rental pricelist
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
Input
Output
Description
Type
Variable name
Type of car
Character
code
Number of days
Integer
noDay
Amount due
Real
amtDue
Table 14: Input and output variables for Example 6
Ed 3 BPP 4th pgs.indb 92
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
Input
Processing
Output
code
Prompt for input values
amtDue
noDays
Enter input values
•
93
Validate data
Calculate amtDue
Display amtDue
Table 15: IPO chart for Example 6
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
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.
Ed 3 BPP 4th pgs.indb 93
2012/11/26 2:45 PM
94
•
BASIC PROGRAMMING PRINCIPLES
Test the program as follows:
Type of car
Number of days
Small
4
Large
3
Grand
9
Medium
K
Output:
Enter the type of car you need S, M or L: S
Enter number of days for car hire: 4
The amount due is R700.00
Enter the type of car you need S, M or L: L
Enter number of days for car hire: 3
The amount due is R1200.00
Enter the type of car you need S, M or L: G
Enter number of days for car hire: 9
Wrong code entered, only S, M or L is valid. You entered the code G
Enter the type of car you need S, M or L: M
Enter number of days for car hire: K
Number of days entered not numeric. You entered K
Exercises
1. Write only the nested if statements without logical operators for each of
the following problem statements. You can assume that all the variables
contain valid values. Choose your own variable names where applicable.
1.1 Calculate the medical aid contribution of an employee calculated
according to the values in Table 16. You can assume that the salary is
stored in the variable called salary and the number of dependants is
stored in the variable noDepend.
Monthly salary
Dependants
Percentage of salary
0 – 4999.99
Any number
0
1 or more
2%
5000 and more
4%
3.5%
Table 16: Medical aid contributions
Ed 3 BPP 4th pgs.indb 94
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
95
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.
Ed 3 BPP 4th pgs.indb 95
2012/11/26 2:45 PM
96
•
BASIC PROGRAMMING PRINCIPLES
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
5
8
-5
-6
-3
-3
10
5
z
Table 17: Values of x and y
Ed 3 BPP 4th pgs.indb 96
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
97
4. Carefully study the following problem statements. In each case, indicate
the variables used, draw an IPO chart and write an algorithm to solve
the problem. Create a trace table for every odd-numbered question using
carefully selected test data.
4.1 Poppy, who counts every cent to get the best value for her money,
needs to buy washing powder. She went to the shop and wrote
down the prices of the 500 g, 750 g and 1 kg packets of her favourite
washing powder. She wants to write a program to determine
which one of the packets is the best buy (most economical). Do
the calculations and display which packet she should buy. The user
should be prompted to enter the prices for all three packets.
You can test your program with the following test data:
500 g
R14.85
750 g
R21.95
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
Table 18: Income tax on interest earned
Ed 3 BPP 4th pgs.indb 97
2012/11/26 2:45 PM
98
•
BASIC PROGRAMMING PRINCIPLES
4.3. The Anything Company employs representatives who sell products
to the public. These representatives (code = REP) are grouped
into areas. Each area has an area manager (code = AM). A region
contains five areas and has a regional manager (code = RM). Each
representative receives a 20% commission on sales, whereas his/her
area manager receives 5% on it and the regional manager receives
2% on it. Area managers and regional managers may also sell
products.
Therefore:
• If the representative sells the products, he/she gets commission
(20%), the area manager gets commission (5%) and the regional
manager gets an amount (2%),
• If the area manager sells the products, he/she gets commission
(20% + 5%) as well as the regional manager, who gets 2%,
• If the regional manager sells the products, he/she gets all the
commission (20% + 5% + 2%).
The user enters a representative’s name, code and amount of sales.
Provide for incorrect input values. Depending on the code, calculate
and display the commission for each person.
Examples:
• Code REP – display the commission for the representative, area
manager and regional manager,
• Code AM – display the commission for the area manager and
regional manager,
• Code RM – display the commission for the regional manager.
2 The Select Case structure
Like nested if statements, select case structures are used to perform processing
steps depending on the outcome of a tested condition. However, case structures
are used when the same variable is tested for many different values.
Study the following if statement:
if number = 1 then
display “Group 1”
else
if number = 3 then
display “Group 3”
else
display “Group unknown”
endif
endif
Ed 3 BPP 4th pgs.indb 98
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
99
The same condition can be tested in a select case statement, which is much
easier to read.
select case number
case 1
display “Group 1”
case 3
display “Group 3”
case else
display “Group unknown”
endselect
~ Indicate the variable to be tested
~ If no match is found
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.
select case noItems
case 1 to 10
percentage = 5
display “*”
case 11 to 20
percentage = 6.4
display “$”
case > 20
percentage = 7
display “#”
endselect
amount = (noItems * price) – (noItems * price * percentage / 100)
display “The amount is R ”, amount
Ed 3 BPP 4th pgs.indb 99
2012/11/26 2:45 PM
100
•
BASIC PROGRAMMING PRINCIPLES
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.
Grade
Processing of price
A
Double the price
B
Add VAT of 14%
C
Deduct a discount of 8.75%
Add R5 if the price is higher than R50
Subtract R4 if the price is equal to R50 or lower
Other
Table 19: Price according to grade
select case grade
case “A”
price = price * 2
case “B”
price = price * 1.14
case “C”
price = price * 0.9125
case else
if price > 50 then
price = price + 5
else
price = price – 4
endif
endselect
~ (1 - 0.0875 = 0.9125)
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.”
select case name
case “Sally”, “Tania”
display “She is a girl.”
case “Jim”, “John”, “ Russell”
display “He is a boy.”
endselect
Ed 3 BPP 4th pgs.indb 100
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
101
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!
Pages read
Minutes
0 – 20
0
21 – 50
10
51 – 100
40
More than 100
75
Table 20: Minutes per number of pages
Planning
Input
Output
Description
Type
Variable name
Number of pages
Number of
minutes
Error message
Integer
pages
Integer
minutes
String
message
Table 21: Input and output variables for Example 9
Input
Processing
Output
pages
Prompt for pages
minutes
Enter pages
message
Calculate minutes
Display minutes and
message
Table 22: IPO chart for Example 9
Ed 3 BPP 4th pgs.indb 101
2012/11/26 2:45 PM
102
•
BASIC PROGRAMMING PRINCIPLES
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
Test data: Pages = 45, 432, -6, 255, x
Output:
Enter the number of pages read: 45
Good girl! You may watch TV for 10 minutes.
Enter the number of pages read: 432
The pages must be > 0 and not more than 400.
Enter the number of pages read: -6
The pages must be > 0 and not more than 400.
Ed 3 BPP 4th pgs.indb 102
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
103
Enter the number of pages read: 255
Good girl! You may watch TV for 75 minutes
Enter the number of pages read: 16
You must read more than 20 pages to watch TV. Better luck next time.
Exercises
1. Write only the select case statements for the following problem
statements.
1.1 If the value of K is equal to 3, increase the value of A by 5%. If the
value of K is equal to 4, decrease the value of A by 8. If the value
of K is equal to 7, add the value of B to the value of A, otherwise
decrease the value of A by 12%.
1.2 If the integer variable called xyz contains a value of 3, 8 or 9, display
three asterisks, but if xyz contains a negative value, display five
asterisks. However, if the value is between 10 and 20, then display
seven asterisks. If xyz contains any other value, display four equals
signs.
1.3 Change the value of the variable called X based on the value of A,
as given in Table 23. A and X contain positive values; X is a variable
with a real value and A is variable with an integer value.
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
Table 23: Actions to be taken regarding X, depending on the value of A
1.4 The marital code of a person is stored in the variable called
marCode. Display the corresponding description on the screen.
Provide for an incorrect marital code.
S = single
M = married
D = divorced W = widowed
Ed 3 BPP 4th pgs.indb 103
2012/11/26 2:45 PM
104
•
BASIC PROGRAMMING PRINCIPLES
1.5 The commission that a salesperson earns is stored in the variable
called income. The salesperson also earns a bonus, based on the sales
that are stored in the variable called sales, as given in Table 24.
Sales in Rand
Bonus in Rand
0 - 5 000
0
5 001 - 10 000
500
10 001 - 35 000
1 500 + 0.5% of sales
35 001 and more
4 000 + 1% of sales
Table 24: Bonus sliding scale
2. Display the bonus using a select case statement.
2.1 Rewrite the following if statement as a select case statement.
if code = “S” then
Sport = “Soccer”
else
if code = “R” then
Sport = “Rugby”
else
if code = “T” then
Sport = “Tennis”
else
if code = “H” then
Sport = “Hockey”
else
if code = “B” then
Sport = “Basketball”
else
Sport = “Unknown”
endif
endif
endif
endif
endif
2.2 Rewrite the select case statements in Examples 7 and 8 as nested if
statements.
3. Study the following problem statements carefully. In each case, indicate
the variables used, draw an IPO chart and write an algorithm to solve the
problem.
3.1 Rewrite the nested if statement you wrote in Section 1, Exercise 4.2
as a select case statement.
3.2 Enock runs a gardening service that charges by the hour on a sliding
scale, as given in Table 25. He also charges an additional R2.50 per
hour for equipment used. Enter the hours worked as a real number
Ed 3 BPP 4th pgs.indb 104
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
105
and calculate and display the amount owed to him. Use a select case
statement to calculate the amount.
Hours worked
Payment per hour
0–2
R20.00
>2 – 4.54
R19.20
4.6 – less than 6
R18.20
6 hours and more
R17.88
Table 25: Hourly rate sliding scale
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.
Ed 3 BPP 4th pgs.indb 105
2012/11/26 2:45 PM
106
•
BASIC PROGRAMMING PRINCIPLES
3.7 FRIENDLY CONSUMER is an application that gives advice about
various products to consumers. The user must enter the description
of a product as well as the current price and the price one year ago.
The algorithm must then evaluate whether the current price is less
than, equal to or greater than the price one year ago. If greater than
(which is more than likely), the difference between these two prices
must be calculated. The algorithm must display a message advising
the user to buy a product only if the price remained the same or
decreased (which is unlikely).
If there was an increase in the price, the algorithm must calculate
the percentage increase and compare it with the current rate of
inflation of 6.3%. If the increase percentage is less than or equal
to the inflation rate, the user must be advised to buy the product.
However, users must be advised not to buy a product if the price
rose more than the inflation rate.
3.8 At the ABC cellphone company, the price of a phone call using an
ABC cellphone depends on the length of the call and the connection
type, as given in Table 26. Type A clients get a 10% discount on all
calls.
An ABC cellphone
Price in R/c per minute
or part thereof
.90
Other cellphone
1.35
Landline
1.90
Connection type
Table 26: ABC cellphone tariffs
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.
Ed 3 BPP 4th pgs.indb 106
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
107
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.
4.
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.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
Ed 3 BPP 4th pgs.indb 107
2012/11/26 2:45 PM
108
•
BASIC PROGRAMMING PRINCIPLES
4.2 Identify the mistake in the following if statement.
if salary < 20000 then
if salary > 25000 then
salary = salary + 1000
else
salary = salary + 500
endif
endif
5. Write down the exact output of each of the following groups of
statements.
5.1
a=5
b=7
c = 14
if (a + b) >= (c + 3) then
display “The answer is *”
else
if (c – a) <= (b + 2) then
display “The answer is %”
else
display “The answer is #”
endif
endif
~ Display on new line
~ Display on new line
~ Display on new line
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
Ed 3 BPP 4th pgs.indb 108
2012/11/26 2:45 PM
THE SELECTION CONTROL STRUCTURE: PART 2
•
109
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
Ed 3 BPP 4th pgs.indb 109
2012/11/26 2:45 PM
110
Chapter 6
Iteration using a fixed
count loop
Introduction
Programming often involves repeating a set of instructions a number of
times. Sometimes we know exactly how many times we need to repeat the
instructions, and other times we don’t. This type of programming is called
iteration or looping. In this chapter, we’ll discuss the for loop where we know
exactly how many times to repeat a set of instructions. This is sometimes called
a fixed count loop or an automatic count loop.
Outcomes
When you have studied this chapter, you should be able to:
• write a loop in pseudocode using a for-next statement,
• explain the purpose of an accumulator and implement it in a solution, and
• know when to display output during every execution of a loop and when to
display it at the end of the loop.
1 The For-next loop
The syntax of the for-next loop is as follows:
for variable1 = begin-value to end-value [step variable2]
⎫
statement 1
⎪
statement 2
~ Body of the for-next statement
⎬
⎪
statement n
⎭
next variable1
Ed 3 BPP 4th pgs.indb 110
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
•
111
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, “ “
k=k+1
next i
~ On the same line
The output will be:
1 2 3 4 5 6 7 8 9 10
Note the space (“ “) in the display statement, which ensures that the output is
more readable.
This for-next statement can be written more effectively using the index i,
as follows:
for i = 1 to 10
display i, “ “
next i
~ On the same line
These statements will produce the same result.
Ed 3 BPP 4th pgs.indb 111
2012/11/26 2:45 PM
112
•
BASIC PROGRAMMING PRINCIPLES
i=1
Yes
i > 10?
No
i, ” ”
i=i+1
Figure 1: Flowchart of the For-next statement using an index
Example 2
The for-next statement is changed to display the consecutive numbers
from 1 to 10 in descending order. This means that the step must be negative
and the statements must change, as follows:
for i = 10 to 1 step -1
display i, “ “
next i
Ed 3 BPP 4th pgs.indb 112
~ On the same line
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
•
113
The output will now be:
10 9 8 7 6 5 4 3 2 1
i = 10
Yes
i < 1?
No
i, ” ”
i=i−1
Figure 2: Flowchart of the For-next statement with a negative step
Ed 3 BPP 4th pgs.indb 113
2012/11/26 2:45 PM
114
•
BASIC PROGRAMMING PRINCIPLES
Questions
What will the output of the following for-next loops be?
1. for x = 0.5 to 5.5 step 0.5
display x, “ “
next x
2. for x = 1 to 15 step 2
display x, “ “
next x
3. for x = 2 to 18 step 3
display x
next x
4. for y = 5 to 0 step -1
display y
next y
~ On the same line
~ On the same line
~ On a new line
~ On a new line
Example 3
The sum of the first five odd numbers is calculated and displayed.
sum = 0
~ Initialise the value of sum in the beginning
odd = 1
~ First odd number
for k = 1 to 5
~ Loop will execute 5 times
sum = sum + odd
~ Add the current odd number to the sum
odd = odd + 2
~ Move to the next odd number
next k
~ Move to the next value of k
display “The sum of the first 5 odd numbers is “, sum
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.
Ed 3 BPP 4th pgs.indb 114
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
•
115
Let’s create a trace table to make this clearer.
Instruction
sum
assignment
0
assignment
odd
1
1
calculation
3
for
calculation
2
4
calculation
5
for
calculation
3
9
calculation
7
for
calculation
4
16
calculation
9
for
calculation
calculation
for
Output
1
for
calculation
k
5
25
11
6
display
The sum of the first 5 odd numbers is 25
Table 1: The trace table for Example 3
Note that in this example, the answer is only displayed once, after the loop has
terminated.
The technique used above, to add or summate inside a loop, is sometimes
referred to as accumulation. The variable, sum, is called an accumulator.
Accumulation is often used in problem solving to calculate a total or an
average. When you add 1 to the accumulator during every execution of the
loop, the accumulator is called a counter.
Ed 3 BPP 4th pgs.indb 115
2012/11/26 2:45 PM
116
•
BASIC PROGRAMMING PRINCIPLES
sum = 0
odd = 1
k=1
K > 5?
Yes
No
sum = sum + odd
odd = odd + 2
k=k+1
“The sum of
the first 5 odd
numbers is”, sum
Figure 3: Flowchart representation of Example 3
Ed 3 BPP 4th pgs.indb 116
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
•
117
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
sum = sum + multiple
multiple = multiple + 5
next x
display “Sum =”, sum
end
~ On a new line
Next we’ll test the algorithm using a trace table.
Ed 3 BPP 4th pgs.indb 117
2012/11/26 2:45 PM
118
•
BASIC PROGRAMMING PRINCIPLES
Instruction
sum
assignment
0
assignment
multiple
x
5
display
The first 6 multiples of 5 and their sum
for
1
display
calculation
5
5
calculation
10
for
2
display
calculation
10
15
calculation
15
for
3
display
calculation
15
30
calculation
20
for
4
display
calculation
20
50
calculation
25
for
5
display
calculation
25
75
calculation
30
for
6
display
calculation
calculation
for
Output
30
105
35
7
display
Sum = 105
Table 2: The trace table for Example 4
Note that each multiple of 5 is displayed in the loop and their sum is only
displayed once, after the loop has terminated.
Ed 3 BPP 4th pgs.indb 118
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
•
119
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 fornext 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
Let’s look at some more worked examples that use loops.
Example 6
This example shows the planning and an algorithm to display a series of even
numbers. These two questions must be asked of the user:
• At what even number do you want to start?
• How many even numbers do you want to display?
Ed 3 BPP 4th pgs.indb 119
2012/11/26 2:45 PM
120
•
BASIC PROGRAMMING PRINCIPLES
Planning
Input
Output
Description
Type
Variable name
Even number to start
Integer
beginNo
How many even numbers
Integer
howMany
Output even numbers
Integer
evenNo
Table 3: Input and output variables for Example 6
Input
Processing
Output
beginNo
Prompt for input values
evenNo
howMany
Enter input values
Calculate new even number
Display evenNo
Table 4: IPO chart for Example 6
Algorithm
DisplayEvenNumbers
~ Calculate the desired even numbers
display “ Provide the beginning even number”
enter beginNo
display “How many even numbers must be displayed? “
enter howMany
if beginNo is numeric then
if howMany is numeric and howMany > 0 then
remainder = beginNo MOD 2
if remainder = 0 then
even = beginNo
~ Display on new line
~ Display on new line
~ Test if beginNo is an even
~ number
~ 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
Ed 3 BPP 4th pgs.indb 120
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
•
121
Test the logic with the following four sets of test data:
beginNo = 8, howMany = 10
beginNo = 16, howMany = -3
beginNo = 9, howMany = 15
beginNo = x, howMany = 3
Output:
8 10 12 14 16 18 20 22 24 26
The begin number must be an even number
The number must be numeric and greater than 0
The begin number must be numeric
Questions
1. What will the output be if the user enters -16 as the begin value and 9 for
howMany?
2. What will the output be if the user enters 0 as the begin value and 4 for
howMany?
Exercises
The for-next statement in the DisplayEvenNumbers algorithm can be
changed as follows:
for x = beginNo to ((howMany * 2) + beginNo) step 2
display x
next x
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
Ed 3 BPP 4th pgs.indb 121
2012/11/26 2:45 PM
122
•
BASIC PROGRAMMING PRINCIPLES
lower or higher than the other one. So we’ll declare one variable called lowest
and another called highest. These will contain the lowest and the highest test
marks respectively.
There are two ways to do this:
Method 1
• Assign a very low value to highest (-1 for instance) so that all the current
values compared to this number will be higher.
• Then assign a very high value to lowest (101, for instance) so that all the
current values compared to this number will be lower.
• Then repeat the process ten times.
Method 2
• Assign the mark of the first student to both lowest and highest in order to
compare the current values.
• Repeat the process only nine times, because the first value has already
been dealt with.
We’re going to use the second method in our algorithm. We’ll also assume that
all input values will be valid.
Input
Intermediate
Output
Description
Type
Variable name
Name of student
Student’s test
percentage
Student number
Name of best
student
Highest
percentage
Name of weakest
student
Lowest
percentage
String
stName
Integer
testMark
Integer
st
String
highestName
Integer
highest
String
lowestName
Integer
lowest
Table 5: Input and output variables for Example 7
Input
Processing
Output
stName
Prompt for input values
highestName
testMark
Enter input values
highest
Compare to find results
lowestName
Display output values
lowest
Table 6: IPO chart for Example 7
Ed 3 BPP 4th pgs.indb 122
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
•
123
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
Test the logic using this test data.
Ed 3 BPP 4th pgs.indb 123
2012/11/26 2:45 PM
124
•
BASIC PROGRAMMING PRINCIPLES
Name: Danny
Bill
Don
Dave
Sonny
Edith
Bob
Robbie
Cassandra
Julie
Test percentage: 50
67
92
28
62
54
34
43
64
78
Output:
The name of the student who obtained the highest mark is Don
The highest mark obtained is 92
The name of the student who obtained the lowest mark is Dave
The lowest mark obtained is 28
Example 8
In this program we’re going to do division by subtracting values using a fornext 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
Description
Type
Variable name
Input
Total number
Integer
totNumber
Output
Result
Integer
result
Table 7: Input and output variables for Example 8
Ed 3 BPP 4th pgs.indb 124
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
Input
Processing
Output
totNumber
Prompt for totNumber
result
•
125
Enter totNumber
Subtract 5 from
totNumber until
finished
Display result
Table 8: IPO chart for Example 8
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:
The number can be divided by five 108 times
The number must be greater than 400
The number entered must be an integer
Ed 3 BPP 4th pgs.indb 125
2012/11/26 2:45 PM
126
•
BASIC PROGRAMMING PRINCIPLES
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 fornext 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 fornext 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.
Ed 3 BPP 4th pgs.indb 126
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
•
127
7. There are 30 students in the Programming 1 class. The age of every
student is entered in years and months. Convert the age into months to
calculate the average age. Display the answer (average age) in years and
months on screen.
8. The user must enter a positive integer less than or equal to 15. If this
number is valid, the user must also enter a choice of 1, 2 or 3, which must
result in the following output:
1: Display the first 5 multiples of the number entered and the sum of
these multiples
2: Display all consecutive positive numbers up to this number
3: Display the factorial of this number
Display an appropriate error message only if the choice or the positive
integer number is incorrect. Use a select case structure to handle the
choices.
Examples
Assume a 5 has been entered as a positive integer number. The output may be
one of the following, depending on the choice made.
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
9. Write the algorithms to solve the following problems:
9.1 Calculate and display the sum of the first 20 elements in the following
series:
1; 2; 4; 7; 11; …
9.2 Display the value of the 30th element in the following series on screen:
2400; 2398; 2394; 2388; 2380; ...
Ed 3 BPP 4th pgs.indb 127
2012/11/26 2:45 PM
128
•
BASIC PROGRAMMING PRINCIPLES
10. In each case, predict the output of the given algorithm:
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
2 Nested For statements
In many situations, it is necessary to use a loop contained within another loop.
Example 9
for i = 1 to 2
for j = 1 to 3
next j
next i
~ Outer loop
~ Inner loop statement(s)
~ End of inner loop
~ End of outer loop
A structure like these loops is called a nested loop.
When the nested loops in the example are executed, the values of the counters
i and j will vary when executed, as follows:
Ed 3 BPP 4th pgs.indb 128
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
i
1
1
1
2
2
2
•
129
j
1
2
3
1
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
Description
Type
Variable name
Input
Test marks
Integer
tstMark
Intermediate
Total sum
Integer
totSum
Sum
Integer
sum
Final mark
Integer
finMark
Class average
Integer
average
Output
Table 9: Input and output variables for Example 10
Input
Processing
Output
tstMark
Prompt for input
finMark
Enter tstMark
average
Calculate finMark
Display finMark
Calculate average
Display average
Table 10: IPO chart for Example 10
Ed 3 BPP 4th pgs.indb 129
2012/11/26 2:45 PM
130
•
BASIC PROGRAMMING PRINCIPLES
Algorithm
CalcResults
~ Produce results of students
totSum = 0
for x = 1 to 4
sum = 0
for y = 1 to 3
display “Provide test mark ”, y, “ for student ”, x
enter tstMark
sum = sum + tstMark
next y
~ Calculate final mark for student
finMark = sum / 3
display “The final mark for student ”, x, “ is ”, finMark
totSum = totSum + finMark
next x
~ Calculate and display average
average = totSum / 4
display “The average for all the students is ”, average
end
~ Loop for 4 students
~ Loop for 3 tests
~ End of test loop
~ Add to total sum
~ End of student loop
You can test the logic with this test data:
Tests
1
2
3
1
2
3
4
45
63
23
41
50
68
34
61
55
71
31
59
Students
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
Ed 3 BPP 4th pgs.indb 130
2012/11/26 2:45 PM
ITERATION USING A FIXED COUNT LOOP
•
131
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
next w
display “The answer is: ”, answer
end
~ Display on a new line
~ Display on a new line
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
next x
display “The value of result is ”, result
end
~ Display on a new line
~ Display on a new line
2.3
ShowResults
for x = 1 to 5 step 2
display “x = ”, x
for w = x to 1 step -1
z=x+w
if w > 2 then
display w
endif
next w
display “z = ”, z
next x
display “*****”
end
Ed 3 BPP 4th pgs.indb 131
~ Display on a new line
~ Display on a new line
~ Display on a new line
~ Display on a new line
2012/11/26 2:45 PM
132
•
BASIC PROGRAMMING PRINCIPLES
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 “ d = ”, d
x=x+1
next k
end
~ Display on a new line
~ Display on the same line
3. Do the planning and write an algorithm to solve the following problem.
There are seven libraries, numbered 1 to 7, in the city of Grandioso. Each
library has eight sections of books. Input the number of books for each
section in one library and accumulate the total number of books in the
library.
Hint: Use a nested for loop. Display the number of the library with the
most books and the number of the library with the least books.
Ed 3 BPP 4th pgs.indb 132
2012/11/26 2:45 PM
133
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.
Ed 3 BPP 4th pgs.indb 133
2012/11/26 2:45 PM
134
•
BASIC PROGRAMMING PRINCIPLES
Certain conditions may stop this process, for example:
• All the available tickets have been sold.
• The box office closed at 17:00.
• All the people in the queue have already bought their tickets.
• The box office never opened.
If all these conditions were included in a solution, it is clear that we really
have no idea when the repetition must stop. We need a statement to test these
conditions, otherwise the loop will run forever (endless loop).
There are two types of do loop. When planning a solution that contains
a number of statements to be repeated several times, the programmer has to
decide which type of loop must be used.
1.1 Pre-test loop (Do-while statement)
The first type is called a pre-test loop where the condition is tested before
the statements within the loop are processed. Looking at the box office selling
football tickets, we see that various conditions may occur: there might not be a
queue because no-one wants to buy tickets, all the tickets might have been sold
out yesterday or the person who sells the tickets hasn’t opened the box office.
In this case, no tickets will be sold.
Here’s an example of this type of loop, in which the closing time of the box
office is tested.
do while time <= 1700
statement 1
statement 2
:
statement n
loop
~ Statement to control the loop
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 while time <= 1700 and noTickets > 0
Ed 3 BPP 4th pgs.indb 134
2012/11/26 2:45 PM
I TERATION USING THE DO LOOP
•
135
1.2 Post-test loop (Do-loop-until statement)
The other type of do loop is called a post-test loop. The statements in the
body of the loop are processed at least once, and the condition is tested only
after the statements in the body of the loop have been processed. Consider a
situation in which 100 tickets are available but there are 150 people waiting to
buy tickets. So tickets can be sold only until all the tickets have been sold and
no more tickets are available.
Here’s an example of this type of loop, in which the number of tickets is
tested.
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.
1.3 Terminating execution of a loop
There must be a statement in the body of a loop – in both pre-test and post-test
loops – that enables the outcome of the condition tested in the loop control
statement to change. If this statement is absent, the loop will never end.
Using our ticket sales example, the statement in bold type could cause the
loop to terminate.
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
Another method of terminating a loop is to use a sentinel. Suppose sales must
be entered repeatedly to determine the highest sales. The programmer may
decide to enter a sales amount of -1 to end the loop.
Any suitable value could have been chosen to indicate the end of the
processing, as long as the value is not a valid input to the program. This value
is called a sentinel.
Ed 3 BPP 4th pgs.indb 135
2012/11/26 2:45 PM
136
•
BASIC PROGRAMMING PRINCIPLES
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.
display “Enter a sales amount or -1 to stop”
enter salesAmount
do while salesAmount <> -1
statement 1
statement 2
:
statement n
display “Enter the next sales amount or -1 to stop”
enter salesAmount
loop
1.4 Examples of Do-while loops
As discussed before, this type of loop tests a condition before processing the
statements in the loop. So it’s possible that the body of a do-while loop might
never execute.
Example 1
This example calculates the sum of all the consecutive integers starting at 24
while the sum is less than 23456. It then displays how many integers have been
added to the sum.
CalcSum
~ Accumulate a counter of integers added to a sum
⎫
⎪
sum = 0
~ Initialise sum
⎬
⎪
number = 24
⎭
count = 0 ~ Initialise the counter
do while sum < 23456
sum = sum + number
number = number + 1
count = count + 1
loop
display “The number of integers added is ”, count
end
~ See Comment 1
~ Accumulate the sum
~ Proceed to the next consecutive no
~ Increment count
~ See Comment 2
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.
Ed 3 BPP 4th pgs.indb 136
2012/11/26 2:45 PM
I TERATION USING THE DO LOOP
•
137
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
Input
Output
Description
Name of
fisherman
Number of fish
caught
Most fish
Name of winner
Type
Variable name
String
fmName
Integer
noFish
Integer
winnerNumber
String
winner
Table 1: Input and output variables for Example 2
Ed 3 BPP 4th pgs.indb 137
2012/11/26 2:45 PM
138
•
BASIC PROGRAMMING PRINCIPLES
Input
Processing
Output
fmName
Prompt for input values
Enter fmName and
noFish
Determine winner
Display winner,
winnerNumber
winner
noFish
winnerNumber
Table 2: IPO chart for Example 2
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
Ed 3 BPP 4th pgs.indb 138
2012/11/26 2:45 PM
I TERATION USING THE DO LOOP
•
139
This test data would cover all possible conditions.
Name:
Sam
Johnny
Kevin
Fred
Bill
Ted
Paul
Number of fish:
8
2
7
10
5
12
9
Output:
Provide the number of fish caught by the first fisherman
Enter -1 to indicate no more input 8
Provide name of fisherman Sam
Provide the number of fish caught by the next fisherman
Enter -1 to indicate no more input 2
Provide name of fisherman Johnny
:
:
Provide the number of fish caught by the next fisherman
Enter -1 to indicate no more input 9
Provide name of fisherman Paul
Provide the number of fish caught by the next fisherman
Enter -1 to indicate no more input -1
The name of the winner is Ted
Ted caught 12 fish
Congratulations Ted!!!
Example 3
Alexis went shopping and bought a number of different items. We need to
enter the amount of money in her purse and the price of each item to calculate
the total amount. After all the prices are entered, a price of 0 (zero) is entered
as a sentinel to indicate that she has finished selecting items to buy. If the total
amount she spent is more than R100 she’ll receive a discount of 3.5%. If the
money in her purse is enough to pay for her shopping, we need to calculate
and display how much money she will have left in her purse after she’s received
her change, if any. If she doesn’t have enough money to pay for all the items, a
message is displayed indicating how much more money she needs to pay for
her shopping.
Ed 3 BPP 4th pgs.indb 139
2012/11/26 2:45 PM
140
•
BASIC PROGRAMMING PRINCIPLES
Planning
Input
Intermediate
Output
Description
Type
Variable name
Price of item
Real
price
Money in purse
Real
purseMoney
Total amount
Money left in
purse
Money still
needed
Real
total
Real
change
Real
shortMoney
Table 3: Input and output variables for Example 3
Input
Processing
Output
price
Prompt for input values
Enter price and
purseMoney
Calculate totAmount
change
purseMoney
shortMoney
Test purseMoney
Calculate change or
shortMoney
Display results
Table 4: IPO chart for Example 3
Ed 3 BPP 4th pgs.indb 140
2012/11/26 2:45 PM
I TERATION USING THE DO LOOP
•
141
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
These two sets of data could be used as test data:
Data set 1
The amount in her purse is
R709.55
Item 1
R150.50
Item 2
R285.70
Item 3
R397.42
Desk checking:
The total amount she spent is R833.62
This amount is more than R100, so she receives 3.5% discount
The amount now due is R833.62 – R29.18 = R804.44
She needs R804.44 – R709.55 = R94.89
Ed 3 BPP 4th pgs.indb 141
2012/11/26 2:45 PM
142
•
BASIC PROGRAMMING PRINCIPLES
Data set 2
The amount in her purse is
R75.00
Item 1
R3.00
Item 2
R25.50
Item 3
R21.60
Item 4
R7.80
Desk checking:
The total amount she spent is R57.90
This amount is not more than R100, so she doesn’t get a discount
The amount in her purse is now R75.00 – R57.90 = R17.10
Output:
Alexis needs R94.89 more to pay for her purchases
Alexis has enough money, she now has R17.10 change in her purse
1.5 Examples of Do-until loops
We discussed do-until loops when we covered post-test loops in section 1.2,
explaining that they are used to test a condition at the end of the loop.
Example 4
Angel has offered to pick strawberries for her mother, who wants to make
jam. She needs between 4.5 and 5.5 kilograms of strawberries for the jam.
Angel, who is only a little girl, can pick and carry between 400 and 900 grams
of strawberries at a time, which she puts into her mother’s container on the
scale. The user is asked to enter the weight of the strawberries in grams each
time Angel brings strawberries. The program must calculate and display how
many times she has to go to the garden to pick strawberries before her mother
has enough for jam. The program must also display the total weight of the
strawberries picked.
Planning
Description
Type
Variable name
Input
Weight in grams
Real
weight
Output
Number of times
Real
noTimes
Total weight in kg
Real
totWeight
Table 5: Input and output variables for Example 4
Ed 3 BPP 4th pgs.indb 142
2012/11/26 2:45 PM
I TERATION USING THE DO LOOP
Input
Processing
Output
weight
Prompt for weight
noTimes
Enter weight
totWeight
•
143
Count noTimes
Accumulate totWeight
Display noTimes,
totWeight
Table 6: IPO chart for Example 4
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.
Ed 3 BPP 4th pgs.indb 143
2012/11/26 2:45 PM
144
•
BASIC PROGRAMMING PRINCIPLES
Test data
Possible input values with respective output results:
Enter the weight of the strawberries in grams Angel picked 500
Enter the weight of the strawberries in grams Angel picked 88O
88O is not a valid input value, please re-enter
Enter the weight of the strawberries in grams Angel picked 880
Enter the weight of the strawberries in grams Angel picked 720
Enter the weight of the strawberries in grams Angel picked 450
Enter the weight of the strawberries in grams Angel picked 570
Enter the weight of the strawberries in grams Angel picked 770
Enter the weight of the strawberries in grams Angel picked 360
Enter the weight of the strawberries in grams Angel picked 320
The number of times Angel picked strawberries is 8
She picked a total of 4.570 kg of strawberries
2. Examples of flowcharts for pre-test and posttest 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.
Ed 3 BPP 4th pgs.indb 144
2012/11/26 2:45 PM
I TERATION USING THE DO LOOP
•
145
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.
Ed 3 BPP 4th pgs.indb 145
2012/11/26 2:45 PM
146
•
BASIC PROGRAMMING PRINCIPLES
Figure 2: Flowchart representing a Do-until loop
The loop in Figure 2 is clearly a post-test loop because the condition is tested
at the end of the statements in the body of the loop, so the loop will always
execute at least once. Because this loop will execute until the condition is true,
the condition will be the opposite of the condition in the do-while example in
Figure 1.
Ed 3 BPP 4th pgs.indb 146
2012/11/26 2:45 PM
I TERATION USING THE DO LOOP
•
147
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
w = 0
do while w < 10
w = w + x * 3
z = x + w
if w > 12 then
display w
endif
loop
display “z = ”, z
next x
display “*****”
end
Ed 3 BPP 4th pgs.indb 147
~ Display on a new line
~ Display on a new line
~ Display on a new line
~ Display on a new line
2012/11/26 2:45 PM
148
•
BASIC PROGRAMMING PRINCIPLES
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
loop
display “k = ”, k, “ w = ”, w
end
~ Display on a new line
~ Display on a new line
2.5
ShowResults2-5
x=5
y=7
display “Begin”
for a = 1 to 12 step 5
display “a = ”, a
do
z=a*x+y
y=y–1
x=x+1
loop until y < 7
display “y = ”, y
next a
display “x = ”, x
display “a = ”, a
display “z = ”, z
display “End”
end
~ Display on a new line
~ Display on a new line
~ Display on a new line
~ Display on a new line
~ Display on a new line
~ Display on a new line
~ Display on a new line
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”
a=a+1
loop
end
Ed 3 BPP 4th pgs.indb 148
~ Display on a new line
2012/11/26 2:45 PM
I TERATION USING THE DO LOOP
•
149
3.2
AnotherOutputProgram
x=2
y=3
do
x=x+1
do while y <= 5
display “this is output”
y=y+2
loop
display “this is output”
loop until x = 6
display “this is output”
end
~ Display on a new line
~ Display on a new line
~ Display on a new line
4. Do the planning and write an algorithm for the following questions.
Each problem contains a do loop. When planning your algorithm, decide
which type of loop will be best suited to solving the particular problem
(pre-test or post-test). If the problem contains decisions to be made,
decide whether you’ll use an if statement or a select case statement. You
can assume that all the input data for the following questions will be
valid.
4.1 A programmer is asked to do an invoice of a telephone account for a
subscriber. The input to this program is the telephone number dialed
and the length of the call in minutes (integer). The fees are 50 cents
for the first minute and 30 cents for every minute thereafter. The
telephone number and cost of the call must be displayed for every
call. The total amount due by the subscriber must be shown at the
end of the invoice. A telephone number of 9999 serves as a sentinel.
4.2 The salesmen working at the Tall Man Company earn a basic salary
of R1 850 per month. They also earn commission on their sales. On a
sales amount of less than R8 500 they receive 5.5% commission, but if
they sell more, the commission is 9%. Each employee pays 1.5% of his
commission to his manager. Calculate and display the net income for
every salesperson. The input is the name of the sales person and the
sales amount. The program terminates when no sales person name is
entered.
4.3 Angela went to buy groceries but left her purse at home. Luckily she
found R120 in her coat pocket and decided to buy only the necessary
items. She picked a number of items and presented them at the till in
order of necessity. The lady at the till scanned the barcode containing
the price, which was added to the amount due. Determine and
display how many items Angela could buy.
Ed 3 BPP 4th pgs.indb 149
2012/11/26 2:45 PM
150
•
BASIC PROGRAMMING PRINCIPLES
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:
4.5
4.6
4.7
4.8
Ed 3 BPP 4th pgs.indb 150
Department code
Percentage increase
AY
6%
HT
6.3%
KL
6.9%
Other departments
5.8%
Display the employee number and new annual salary of each
employee. At the end of the program, display the total amount for
annual increases as well as the average increase amount per employee.
A ball is dropped from a specific height to be provided in metres.
This is a real number with two decimal places, such as 7.85. The ball
bounces off the ground to a height of half the original height. This
process repeats itself. Calculate how many times it will bounce before
the height is less than 5 centimetres. Display this answer on the
screen.
Pule decided to save money to buy a house. Enter this amount as
well as the amount he will be able to save each month. He earns 0.7%
interest per month while the amount is less than R80,000 and 0.9%
interest per month if the amount is equal to or more than R80,000.
The interest is added to the total amount. Calculate how many
months he will have to save before he has reached his goal. Display
the final amount and the number of months.
A number of people joined the Streamline Club during the first
week of January and the weight of each member was written on their
membership card. During the last week of March everybody was
weighed again and their new weights were written on their cards.
Enter the name, initial weight and current weight for an unknown
number of people. Calculate the weight loss or weight gain and
display the results, which are the name and weight loss or weight gain
with a suitable message. The program must terminate when no name
is entered. The average weight loss or weight gain must then display
with a suitable message.
Jerry is not sure how much money he has, but he knows he has
between R100 and R135 in R1, R2 and R5 coins. The user enters
the price of the item Jerry wants to buy, which doesn’t exceed R100.
Jerry pays for the item he buys by handing one coin at a time to the
salesperson. The value of the coin is entered and is subtracted from
the amount still due. Determine how many coins Jerry uses to pay for
2012/11/26 2:45 PM
I TERATION USING THE DO LOOP
•
151
an item and display this number. Remember that you don’t know how
many coins he has or their denominations. There may be an equal
number of all the coins, no R1 coins or no R5 coins, and so on. Also
calculate and display the amount of change, if any.
4.9 The Walk-In restaurant is very popular among employees in the area
because they provide home-cooked meals consisting of meat and
vegetables already dished up. They provide different meals for men
(code = M) and women (code = L). Children (code = C) pay half the
price of a lady’s meal. The prices are as follows:
Type of meal
Price per meal
Men
R65.50
Ladies
R56.80
The user enters the number of different meals available in the
beginning of the program; that is, for men, women and children.
Every time someone orders one or more meals, the type of meal
and the number is entered. If the meals are available, this number
is subtracted from the relevant total and then the amount due is
calculated and displayed. If there are no meals of that specific type
available, a suitable message is displayed. If fewer meals than the
customer orders are available, a new transaction is started. When
there are no meals left of any type, the algorithm terminates. You can
assume that all the meals will be bought.
If you want to change the program so that not all the meals are sold,
you can use another condition to terminate the program. In this case,
you can also display how many meals, and of what type, are not sold.
4.10 A florist wants to send coupons to her 420 regular customers, based
on the number of orders each customer placed during the past year,
as follows:
Number of orders
Amount on coupon
2–6
The number of orders times R10
7 – 15
The number of orders times R11.50
16 – 30
The number of orders times R14
31 or more
The number of orders times R17
The user is asked to enter the name of the customer and the number
of orders placed. Determine the value of the customer’s coupon and
then display a message on the screen, similar to the following:
Thank you Carol!
You receive a coupon worth R50 to collect lovely flowers!
Ed 3 BPP 4th pgs.indb 151
2012/11/26 2:45 PM
152
•
BASIC PROGRAMMING PRINCIPLES
4.11 The learners at the Clever School pay school fees according to their
grade.
The name and the grade of the learner must be entered. The learners
in Grade 1 pay R14 for the months February to November (excluding
July). The fee increases by R4.50 for every subsequent grade – R18.50
for Grade 2, R23.00 for Grade 3, and so on. Calculate and display the
name and annual school fee for each learner at the Clever School.
At the end, the average annual school fee must be displayed. ABCD
is entered as a name once the details of all the school’s learners have
been entered.
4.12 The manager of the Nutcracker Hotel needs a program to print
invoices for the guests who stay at his hotel. The input to this
program is the name of the guest, the number of nights he or she
spent in the hotel and the number of breakfasts they had. The
number of nights and the number of breakfasts need not be the same.
A guest receives one free night and one free breakfast for every night
spent in the hotel. You can assume that the number of free breakfasts
will never exceed the number of the input breakfasts. The price of
a night is R340 and a breakfast costs R65. The invoice must contain
the name of the guest, the number of nights stayed, the number of
breakfasts, the number of free nights and the final amount due. At the
end of the program, the total amount paid by all the guests must be
displayed. Choose your own sentinel.
4.13 People who want to hire a machine to wash their carpets usually go
to the WishyWashy Company where they can hire any one of three
types of machines – type A, B or C for heavy duty, ordinary and light
washes respectively. The prices are as follows:
Type of machine
Initial cost
A
R50.00
Additional cost per hour or
part thereof
R30.00
B
R62.50
R36.25
C
R74.87
R40.50
The input is the name of the client, the code to indicate the type
of machine, and the time the machine was used (in minutes). The
amount must be calculated by adding the initial cost to the calculated
cost for the time used. VAT of 14% must be added to the amount to
present the final amount due by the client. At the end of the program,
a total amount, total VAT amount and the final total amount due to
WishyWashy must be displayed. Choose your own sentinel.
Ed 3 BPP 4th pgs.indb 152
2012/11/26 2:45 PM
153
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.
Ed 3 BPP 4th pgs.indb 153
2012/11/26 2:45 PM
154
•
BASIC PROGRAMMING PRINCIPLES
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
An element in an array need not have an initial value.
Data type
All the elements in an array must be of the same data type, such as String or
Integer. Examples:
• monthArray will be of data type String
• price may be of data type Real
• quantityInStock will be of data type Integer
Index
The index indicates the position of an element in the array. The index is
sometimes referred to as a subscript. The value of an index must always be a
positive integer or zero.
The index of the first element of an array is always 0 (zero) and the index
of the last element of the array is (number of elements – 1). For example, the
indexes of an array called mathScores, which contains 30 elements, would start
at 0 so the last index would be 29.
The monthArray array can be visualised as a column with 12 row elements.
Ed 3 BPP 4th pgs.indb 154
2012/11/26 2:45 PM
ARRAYS
monthArray (0)
January
monthArray (1)
February
monthArray (2)
March
monthArray (3)
April
monthArray (4)
May
monthArray (5)
June
monthArray (6)
July
monthArray (7)
August
monthArray (8)
September
monthArray (9)
October
monthArray (10)
November
monthArray (11)
December
•
155
Table 1: monthArray as a column
Referencing
To refer to a specific element in an array, the name of the array as well the
index of the element is used. For instance, monthArray(0) refers to the string
value “January” and monthArray (11) refers to the string value “December”.
Question
Let’s see if you understand the previous concepts by applying them to a similar
example.
The names of the days in a week can be stored in an array. Each element is
called day and an index is used to retrieve the individual values from the array.
Fill in the missing indexes and references in these tables.
Element reference
Value
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
How do you retrieve the third element in the array?
Would it be valid to use day(7) in your code?
Would it be valid to use day(no) in your code if no has a value of 0?
Ed 3 BPP 4th pgs.indb 155
2012/11/26 2:45 PM
156
•
BASIC PROGRAMMING PRINCIPLES
1.1 Advantages of using a one-dimensional array
A one-dimensional array is the simplest form of array, consisting of one
column of elements as illustrated in the examples in the previous section. We
will now start off by explaining why arrays provide a way to improve code to
make it shorter and more efficient.
Let’s assume that a student has written 10 tests in one subject. The final
mark must be calculated as the average of these 10 test marks. If we only had
simple variables – also called scalar variables – we would have to have 10
individual variables to store the 10 test marks. Values for these 10 variables
would have to be entered 10 times when using them to calculate the final mark
for the student.
This is what the algorithm would look like:
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
Ed 3 BPP 4th pgs.indb 156
2012/11/26 2:45 PM
ARRAYS
•
157
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.
Ed 3 BPP 4th pgs.indb 157
2012/11/26 2:45 PM
158
•
BASIC PROGRAMMING PRINCIPLES
Planning
Description
Input
Intermediate
Output
10 test marks
entered in an
array
Total of these
marks
10 test marks
entered in an
array
Final mark
Type
Variable/array
name
Integer
testMark
Integer
totalMark
Integer
testMark
Real
finalMark
Table 2: Input and output variables for Example 1
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:
Ed 3 BPP 4th pgs.indb 158
2012/11/26 2:45 PM
ARRAYS
testMark(0)
60
testMark(1)
65
testMark(2)
77
testMark(3)
45
testMark(4)
87
testMark(5)
93
testMark(6)
74
testMark(7)
39
testMark(8)
45
testMark(9)
70
totalMark
655
finalMark
65.5
•
159
Table 3: Tabular representation of Example 1 array
Example 2
Problem
In this example, Example 1 will be rewritten to calculate the final mark as
the average of the nine best marks. In this case, the lowest mark must be
determined and subtracted from the total before the average is calculated.
Algorithm
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
Ed 3 BPP 4th pgs.indb 159
2012/11/26 2:45 PM
160
•
BASIC PROGRAMMING PRINCIPLES
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
Ed 3 BPP 4th pgs.indb 160
2012/11/26 2:45 PM
ARRAYS
•
161
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
We can then modify the example to start at any even number.
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.
Ed 3 BPP 4th pgs.indb 161
2012/11/26 2:45 PM
162
•
BASIC PROGRAMMING PRINCIPLES
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:
The highest value in the noInStock array is: 658
It was found at index position 9
Note that the index of the first value used in the loop structure is not that of the
first element, because the value of the first element has already been assigned
to the variable called highest.
Exercises
1. Write an algorithm for the following:
An array called numbers contains 35 valid integer numbers. Determine
and display how many of these values are greater than the average value
of all the values of the elements.
Hint: Calculate the average before counting the number of values higher
than the average.
2. An array called abcArray has 12 integer elements. Populate the array
using the values of the series 1 000; 989; 967; 934; 890; ... Display the
values of all the elements.
3. An array that has 20 elements contains character values. Use a Select
Case statement to count and display how many of these elements contain
vowels.
4. You’re given two arrays. The first has 100 elements containing integer
values. The second has 20 elements. Write an algorithm to calculate the
sum of the values of the first five elements of the first array and store the
answer in the first element of the second array. Store the sum of the next
five elements of the first array in the second element of the second array,
and so on.
Ed 3 BPP 4th pgs.indb 162
2012/11/26 2:45 PM
ARRAYS
•
163
For example:
3 7 4 5 9 8 3 4 6 8 3 2 6 7 5 3 4 etc.
First array:
Second array:
28
29
23
etc
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(i) = number(i+1)
number(i - 1) = i + number(i)
next i
Ed 3 BPP 4th pgs.indb 163
number
2012/11/26 2:45 PM
164
•
BASIC PROGRAMMING PRINCIPLES
7. An array called letterArray has 30 elements that contain a sentence with
one letter per element. For example, TODAY IS A LOVELY SUNNY
DAY.
T O D A Y
I
S
A
L O V E
L Y
S U N N Y
D A Y
The following algorithm attempts to count how many elements contain
either an A or an E and displays the count. It must also express the count
as a percentage of the total letter count. Identify and correct all the errors
in this algorithm.
CountAE
count = 1
for k = 1 to 30
if letterArray(i) = “A” OR letterArray(i) = “E” then
count = count + 1
endif
next
percentage = count / k * 100
display “There are ”, k, “ A’s and E’s in the array”
display “The A’s and E’s are ”, percentage, “ % of the total number of letters”
end
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
Ed 3 BPP 4th pgs.indb 164
2012/11/26 2:45 PM
ARRAYS
•
165
9. Given an array called array_s:
array_s
4
7
2
3
8
5
1
9
Determine the value of t after these statements have been processed:
a = -2
t=7
for i = t to 1 step -2
t = t + array_s (i)
t=t+a
a=a*2
next i
display t
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
Ed 3 BPP 4th pgs.indb 165
2012/11/26 2:45 PM
166
•
BASIC PROGRAMMING PRINCIPLES
11.1 What will the value of answer be after the following statements
have been executed?
x=8
answer = XYZ(3) + XYZ(x) + x
11.2 What is the value of element 4?
12. The array called number contains the following values:
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(i) = number(i+1)
number(i+3) = i + number(i)
next i
Ed 3 BPP 4th pgs.indb 166
number
2012/11/26 2:45 PM
ARRAYS
•
167
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(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
priceVal
14. The array XYZ can contain 10 numeric elements. Process the code given
below and show the new values in the array.
k=4
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
Ed 3 BPP 4th pgs.indb 167
XYZ
2012/11/26 2:45 PM
168
•
BASIC PROGRAMMING PRINCIPLES
15. An array called ABC consists of 10 elements. It currently has no values
but may contain integer values. Indicate (in the space provided) what the
values in the array called ABC will be after execution of the following
statements:
FillArray
ABC(0) = 1
for x = 1 to 9
ABC(x) = ABC(x – 1) * 2
next x
for z = 9 to 0 step -3
ABC(x) = x + z
next z
Temp = ABC(6)
ABC(6) = ABC(2)
ABC(2) = Temp
for y = 0 to 9
if ABC(y) > 10 then
ABC(y) = ABC(y) + 10
endif
next y
ABC(0) = y
end
ABC
16. An array called NUM contains 50 unique integers. In pseudocode, write
only the statements required to enter values into this array. For each
number entered, ensure that it is numeric and that it does not yet appear
in the array. If a value already exists, display an appropriate error message
and re-enter the value.
17. Write an algorithm for the following:
17.1 Solomon sells 40 different products in his fast food store, which he’s
numbered from 1 to 40. He has decided to use a program to handle
his sales. But first a short program must be developed to load the
prices into the array in the program.
17.2 Add statements to the algorithm to calculate the amount due by a
client. The client orders items according to product number, giving
the required quantity. For every product, the product number,
quantity ordered, unit price and amount for these products must
be displayed. The amount due by the client is displayed once the
product code = 99 is entered.
Ed 3 BPP 4th pgs.indb 168
2012/11/26 2:45 PM
ARRAYS
•
169
2 Parallel (paired) arrays
When two or more arrays are related to one another and have the same number
of elements, they are known as parallel arrays. The elements in these arrays
need not be of the same data type.
Consider two arrays – one called code and the other called description. The
array called code contains the following item codes by which they are identified
(ab3, kh8, vs1, gp5 and wd4), whereas the array called description contains
the following descriptions to match the corresponding elements (chair, table,
bed, cupboard and sofa). In other words, the indexes of the two arrays will be
equivalent for a specific item.
The two arrays can also be represented as follows:
index
code
index
description
0
ab3
0
chair
1
kh8
1
table
2
vs1
2
bed
3
gp5
3
cupboard
4
wd4
4
sofa
Table 4: Content of the code and description arrays
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.
Ed 3 BPP 4th pgs.indb 169
2012/11/26 2:45 PM
170
•
BASIC PROGRAMMING PRINCIPLES
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.
Snack code
Description
Price in R
75
Chocolate
5.75
23
Soda
6.25
89
Pizza slice
8.50
41
Burger
15.85
17
Muffin
5.75
Table 5: Three related arrays
Ed 3 BPP 4th pgs.indb 170
2012/11/26 2:45 PM
ARRAYS
•
171
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
Table 6: A one-dimensional array
Ed 3 BPP 4th pgs.indb 171
2012/11/26 2:45 PM
172
•
BASIC PROGRAMMING PRINCIPLES
This one-dimensional array can be expanded to a two-dimensional array when
the maximum temperatures are added, as follows:
3
18
4
22
5
23
3
21
2
24
3
19
6
25
Table 7: A two-dimensional array
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 twodimensional 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.
Ed 3 BPP 4th pgs.indb 172
2012/11/26 2:45 PM
ARRAYS
•
173
Planning
The following arrays will be used:
Student numbers
stNums
one dimensional
20 rows
Student names
stNames
one dimensional
Student marks
stMarks
two dimensional
Final marks
stFinalMarks
one dimensional
20 rows
20 rows, 4
columns
20 rows
Table 8: Planned arrays for Example 7
Other variables used:
The best mark
A student’s total marks
Variable for student loop
Variable for test loop
best
total
st
test
Algorithm
CalcResults
~ The program will calculate the results of students
for st = 0 to 19
total = 0
for test = 0 to 3
total = total + stMarks(st, test)
next test
stFinalMark(st) = total / 4
~ Loop student 20 times
~ Initialise the total for 1 student
~ Loop test 4 times
~ Add mark of student to his/her total
~ 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
Ed 3 BPP 4th pgs.indb 173
2012/11/26 2:45 PM
174
•
BASIC PROGRAMMING PRINCIPLES
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 twodimensional array, which represents the 12 months of the year, contains
the amounts that the customer spent in the shop, but has not yet paid.
The program must increase the account limits for every customer who
owes less than 75% of the current limit by 12%.
3. The Best Buys supermarket uses a one-dimensional array to store
department codes consisting of three characters each, and a twodimensional array to store the sales for the past month per department.
The two-dimensional array stores information for seven departments
and every department can store 1 000 sales transactions. The seven
department codes must be entered in the beginning of the program
and all the sales amounts must be initialised. The sales transactions are
entered into the two-dimensional array by entering the department code
and the sales amount.
Use the department code to find the index of the department and insert
the amount into the next available element. At the end of the program
the department code and the total sales amount must be displayed. Write
code to eliminate all possible errors including more than 1 000 sales per
department.
4. Two parallel arrays store the following information for seven employees.
The first array is a one-dimensional array that contains the seven
employee numbers. The second array is a two-dimensional array that
contains the basic monthly salary in the first column, the bonus in the
second column and the net salary in the third column. Therefore, every
row in the two-dimensional array will contain the basic monthly salary,
bonus and net salary for the employee whose number is stored in the
parallel array in the same position.
Ed 3 BPP 4th pgs.indb 174
2012/11/26 2:45 PM
ARRAYS
Emp no
B Month Sal
Emp 1
1234
5000.00
Emp 2
2345
6000.00
Emp 3
3456
6500.00
Emp 4
4567
7000.00
Emp 5
5678
8650.00
Emp 6
6789
9800.00
Emp 7
7890
9950.00
Bonus
•
175
Net salary
Table 9: Parallel arrays to use with Question 4
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
Ed 3 BPP 4th pgs.indb 175
2012/11/26 2:45 PM
176
•
BASIC PROGRAMMING PRINCIPLES
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
Table 10: An unsorted array
36
20
15
5
4
Table 11: The array sorted in descending order
Example: The programmer needs to find if the number 16 is present in the
array.
When searching the unsorted array, all the elements are compared to 16
before it is clear that 16 is not present. But when searching the sorted array,
there will only be 3 comparisons, to the values 36, 20 and 15 where the last
value is less than 16 when it is evident that 16 is not in the array.
When using character or string values, the order is:
Ascending:
A to Z
Descending:
Z to A
Remember that the names in a telephone directory are sorted in ascending
sequence.
Ed 3 BPP 4th pgs.indb 176
2012/11/26 2:45 PM
ARRAYS
•
177
4.1 The bubble sort method
There are many sorting techniques. One of the simplest to understand is a
technique called the bubble sort. Elements in the array are compared to each
other in pairs, and when an element is not in sequence, it trades places with
the other element.
We’ll illustrate this concept using an example, as shown in the following
array.
25
47
Comparing the first two elements: 25 is less than
47. Nothing changes.
16
2
17
25
47
Comparing the next two elements: 47 is greater
than 16. Values are swapped.
16
2
17
25
16
Comparing the next two elements: 47 is greater
than 2. Values are swapped.
47
2
17
25
16
Comparing the next two elements: 47 is greater
than 17. Values are swapped.
2
47
17
25
16
At this stage, you will notice that the highest value
(47) is in the last position.
2
17
47
Ed 3 BPP 4th pgs.indb 177
2012/11/26 2:45 PM
178
•
BASIC PROGRAMMING PRINCIPLES
Now we’re going to deal with the first four positions.
16
25
Compare the first two elements: 25 is greater than
16. Values are swapped.
2
17
47
16
2
Comparing the next two elements: 25 is greater
than 2. Values are swapped.
25
17
47
16
2
Comparing the next two elements: 25 is greater
than 17. Values are swapped.
17
25
47
At this stage, you will notice that the second highest value (25) is in the second
last position.
We would continue comparing the values the first three positions in the
same manner, then the first two positions, after which the values in the array
would be in ascending order.
Example 8
Problem
An array called petNames has 15 elements, each of which contains the name of
a pet. The values of the elements must be sorted in ascending sequence.
Ed 3 BPP 4th pgs.indb 178
2012/11/26 2:45 PM
ARRAYS
•
179
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
4.2 The selection sort method
The selection sort method selects the smallest value from the entire array
and exchanges it with the first element in the array. Following this exchange,
the second smallest element is selected from the array and exchanged with the
second element. This process is continued until the entire array is in ascending
order.
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
Table 12: An ascending selection sort
The arrows in the table indicate the movements of the smaller numbers. Note
that they’re exchanged with bigger numbers.
To sort an array into descending sequence, the entire process is just reversed
to start with the biggest value, which is exchanged with the first element in the
array, and so on.
Ed 3 BPP 4th pgs.indb 179
2012/11/26 2:45 PM
180
•
BASIC PROGRAMMING PRINCIPLES
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.
Ed 3 BPP 4th pgs.indb 180
2012/11/26 2:45 PM
181
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.
Ed 3 BPP 4th pgs.indb 181
2012/11/26 2:45 PM
182
•
BASIC PROGRAMMING PRINCIPLES
1 Modules and modularisation
Modularisation divides the solution to a problem into smaller pieces – called
modules – to improve the flexibility of a program and shorten its development
time. A module is therefore part of a program. Large and complex programs
can be divided into independently developed modules. Each module is made
up of one or more statements to perform a specific task. The various modules
are then linked to form a working program.
Modules can take several forms, depending on the programming language
used. Two such forms are function procedures and subprocedures, which we’ll
be discussing in this chapter.
2 Hierarchy charts
A hierarchy chart is a diagram that provides a global view of the modules in
your program and how they link together to function as a complete program.
A hierarchy chart doesn’t contain any detail, just the name of each module and
an indication of how the modules are related.
When drawing a hierarchy chart, you always start by placing the main module
at the top. Through connecting lines, you can then see which modules will be
called from the main module. These modules, in turn, can call other sub modules.
Once a programmer has identified all the steps required to solve a problem,
he or she can group steps that have a common goal into logical groups to see
which of the steps can be coded in a separate module, to break the problem
into smaller chunks and simplify the process.
For example, to calculate students’ final marks, the programmer may
decide to use one module to obtain the input values and two more modules to
calculate the year mark and the final marks. The displaying of the final marks
could also be done in a separate module. Figure 1 shows a sample hierarchy
chart based on this program.
StudentMainModule()
GetInput()
Calculations()
CalcPredicate()
DisplayOutput()
CalcFinalMark()
Figure 1: A hierarchy chart
Note that each module has a descriptive name.
Ed 3 BPP 4th pgs.indb 182
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
•
183
3 Parameters
Before we can study function procedures and subprocedures, we need to
understand what parameters are. A parameter is data (variables or values)
that is sent to a function or a subprocedure, which it needs to perform the
task it has to do. A parameter may also contain the address of an answer when
dealing with a subprocedure.
There are two types of parameters:
• value parameters and
• reference parameters.
3.1 Value parameters
Value parameters can be explained using examples from everyday life.
Joseph has a page on which he wrote some numbers. He makes a copy of
the page and sends it to Solly. In programming terms, Joseph has sent value
parameters to Solly, who could be a function or subprocedure that needs the
parameters.
Solly may do anything he wishes with the parameters because Joseph still
has the original and doesn’t need the copy anymore. So if Solly changes a value
parameter, it is changed only on his copy and not on the original.
Solly may use these parameters to calculate a total. He may keep this total
for his own use or he could return it to Joseph. If he keeps it, the total could be
displayed or it can be used in other calculations. If he returns the value of the
total to Joseph, Solly is a function and not a subprocedure because a function
always returns an answer.
Joseph will now have his original copy as well as a total that doesn’t exist
on his original copy.
Another everyday example is that Sam may tell Henry how much money
he has in his bank account. In programming terms, he’s sending a copy or
value parameter to a function called Henry. Function Henry will now be able
to calculate how much money the two of them have in total, but he cannot
change the amount in Sam’s account.
In the generic planning of programs (algorithms), we will use the prefix val
to identify a value parameter.
3.2 Reference parameters
Again, we can use everyday examples to explain reference parameters.
Josephine receives a post box number and the key to the post box at the post
office. She goes to the post office and opens the box to find a letter in the box.
She can now put something else in the box that the owner will collect. She can
Ed 3 BPP 4th pgs.indb 183
2012/11/26 2:45 PM
184
•
BASIC PROGRAMMING PRINCIPLES
also receive more than one post box number (address) and the corresponding
keys to return different letters to the owners.
In programming terms: Two owners of post boxes give their keys and post
box numbers – two reference parameters – to subprocedure Josephine. This
means that the addresses of the post boxes are known to Josephine and she
has access to the post boxes. In computer terms, these post boxes represent
different areas in memory of the computer. Subprocedure Josephine may now
remove the letter, put another letter in the post box or just write something else
on the letter. But bear in mind that, while the instructions in the subprocedure
apply, changes are issued within subprocedure Josephine. These changes take
place inside the post boxes.
Returning to the banking example in Section 3.1, if Sam gives subprocedure
Henry access to his banking account by giving him the number and pin
code, procedure Henry could withdraw or deposit an amount of money in
Sam’s account. These changes would take place in Sam’s account according to
instructions given by subprocedure Henry.
In the generic planning of programs (algorithms), we will use the prefix ref
to identify a reference parameter.
4 Function procedures
A function procedure, which we’ll refer to as a function, consists of a number
of statements used to execute a single task. A function always returns a value
and can receive value parameters. However, it’s possible that it may not receive
parameters.
4.1 The function call
Calling statements in other parts of the algorithm activate or call a function.
When the function has been processed, control returns to the calling statement.
The list of parameters in a function is known as an argument list.
There are various types of calling statements, such as assignment statements,
if statements and display statements, as can be seen in the following examples.
In each case, the actual call consists of the name of the function followed by an
argument list in brackets. An argument list can, however, be empty.
An assignment statement
Send two values, number1 and number2, to a function named CalcSum, which
will calculate the sum of the two numbers.
Call the function:
sum = CalcSum(number1, number2)
Ed 3 BPP 4th pgs.indb 184
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
•
185
The answer will be stored in sum.
CalcSum is the name of the function whereas number1 and number2 are the
arguments (two value parameters).
A display statement
Use the same example, but don’t store the answer in sum; instead display the
sum of the two numbers.
display “The value of the sum is: ”, CalcSum(number1, number2)
The function CalcSum is called while sending the two value parameters
(number1 and number2) to the function. The sum is returned to the calling
statement and displayed on the screen.
An if statement
if CalcSum(number1, number2) > 40 then
display “The sum is greater than 40”
endif
The function CalcSum is called while passing the two value parameters to the
function to calculate the sum of the two numbers. The sum is returned to the
calling statement and then used in the if statement.
4.2 The function
The first line of a function – called the function header – contains the word
function, a function name and a list of parameters. Again, the parameter list
can be empty.
Format: Function NameOfFunction(parameter list)
The last statement of the function to be processed will be a return statement
(exit the function) that sends the result of the function to the calling statement.
If a function contains an if statement, it may contain more than one return
statement in different parts of the if statement. However, it will execute only
one of these statements and return only one value depending on the outcome
of the if statement. The data type of the value returned must be the same in all
the return statements.
Format: return value
The name of the function is associated with the data type of the value that is
returned to the calling module. This is why a function may return only one
value.
Ed 3 BPP 4th pgs.indb 185
2012/11/26 2:45 PM
186
•
BASIC PROGRAMMING PRINCIPLES
Example:
Write the calling statement to call a function that calculates the sum of two
numbers as well as the function to store the answer in the variable sum.
Calling statement:
sum = CalcSum(number1, number2)
The function to calculate the sum of two numbers will be:
Function CalcSum(valNumber1, valNumber2)
total = valNumber1 + valNumber2
return total
Important notes
• The function name used in the calling statement and the function name
in the function header must always be the same.
• The names of the arguments and parameters need not be the same.
• The order of the variables in a calling statement’s argument list and the
parameters in the function header must always be the same.
• The number of variables in a calling statement’s argument list and the
number of parameters in the function header must always be the same.
• The name of the value returned by the function need not be the same as
in the calling statement.
• The arguments are only the names of the applicable variables in the
calling module. On the other hand, the parameters in the header must
indicate whether the parameter is a value parameter or a reference
parameter – in other words, whether a copy or an address has been sent.
sum = Function Calcsum(number1, number2)
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
Ed 3 BPP 4th pgs.indb 186
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
•
187
4.3 Calling a function and using a function
The examples that follow demonstrate how to do the planning and write
algorithms that use functions and function calls to solve the problem.
Note
In the generic planning for the program examples that follow, we’ll use the
prefixes val for a value parameter and ref for a reference parameter. These
prefixes are used only in the function or subprocedure and not in the calling
module or calling statement.
Example 1
Reginald went to a shop to buy a number of fruit bars. The number bought
and the price of a fruit bar are entered in a main procedure. These numbers
need to be sent to a function to calculate the amount due. The amount due
must include 14% VAT. The calculated value must be returned to the main
procedure and displayed on the screen.
ShoppingProgram()
CalcAmtDue()
Figure 2: Example 1 hierarchy chart
Planning
Description
Type
Variable name
Number of items
Integer
numItems
Price of one item
Real
price
Amount due
Real
amtDue
Integer
valNum
Real
valPrice
Real
-not used-
Main procedure (ShoppingProgram)
Input
Output
Function (CalcAmtDue)
Copy of number
Input
of items
Copy of price of
one item
Output
Amount due
Table 1: Input and output variables for Example 1
Ed 3 BPP 4th pgs.indb 187
2012/11/26 2:45 PM
188
•
BASIC PROGRAMMING PRINCIPLES
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.
Ed 3 BPP 4th pgs.indb 188
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
•
189
ShowResults()
CalcAve()
DetermineResults()
Figure 3: Example 2 hierarchy chart
Planning
Description
Type
Variable name
Student name
String
studentName
Test mark 1
Integer
testMark1
Test mark 2
Integer
testMark2
Test mark 3
Integer
testMark3
Average mark
Real
average
Result
String
-not used-
Integer
valTest1
Integer
valTest2
Integer
valTest3
Real
-not used-
Integer
valAve
String
message
Main procedure (ShowResults)
Input
Output
Function (CalcAve)
Input
Output
Copy of test mark
1
Copy of test mark
2
Copy of test mark
3
Average mark
Function (DetermineResults)
Copy of average
Input
mark
Output
Result message
Table 2: Input and output variables for Example 2
Ed 3 BPP 4th pgs.indb 189
2012/11/26 2:45 PM
190
•
BASIC PROGRAMMING PRINCIPLES
Algorithm
Function CalcAve (valTest1, valTest2, valTest3)
~ Calculate and return the average of the three tests
return (valTest1 + valTest2 + valTest3) / 3
~ Function
Function DetermineResults (valAve)
~ Produce a message to express the outcome
message = “pass”
if valAve < 50 then
message = “fail”
endif
return message
~ Function
ShowResults
~ Main procedure
~ This program determines the result of the student’s performance
display “Enter the student name”
enter studentName
display “Enter the first test mark”
enter testMark1
display “Enter the second test mark”
enter testMark2
display “Enter the third test mark”
enter testMark3
~ Call the function to calculate the average
average = CalcAve (testMark1, testMark2, testMark3)
display “The average mark for ”, studentName , “ is ”, average
~ Call the function to determine the result
display “This student will ”, DetermineResults(average)
end
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
Ed 3 BPP 4th pgs.indb 190
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
•
191
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
loop
end
~ Display on a new line
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
Table 3: Body Mass Index
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.
Ed 3 BPP 4th pgs.indb 191
2012/11/26 2:45 PM
192
•
BASIC PROGRAMMING PRINCIPLES
4.3 Pay = CalcPay(Hours, Tariff )
The function must calculate the person’s pay by multiplying the hours
by the tariff per hour. If there are more than 40 hours, the person
receives 1½ times the tariff for all hours over 40.
4.4 NetMonthSal = CalcSal(GrossAnnSal, TaxPercentage)
The function must calculate and return an employee’s net monthly
salary from their annual gross salary as well as the percentage tax that
the person must pay. Deduct the tax amount from the monthly gross
salary to calculate the monthly net salary.
5. Write a complete algorithm with functions to solve each of the following
problems:
5.1 Enter the radius of a circle, then call one function to calculate the
circumference and another function to calculate the area of the circle.
Display the calculated values on the screen.
5.2 Elize buys a number of boxes of Smarties. You are asked to enter the
number of boxes and the unit price of a box of Smarties. The amount
due is calculated as the number bought multiplied by the price.
However, a customer may receive discount depending on the number
of boxes bought, as can be seen in the table below. All calculations for
the amount due must be calculated in a function. The function must
receive the number bought and unit price. Display the amount due in
the main procedure.
Number of boxes
Discount
1–7
No discount
8 – 20
2.5%
21 and more
4.75%
Table 4: Discount per box
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.
Ed 3 BPP 4th pgs.indb 192
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
•
•
•
•
193
It can receive reference parameters.
It doesn’t return a value.
It is able to manipulate data outside the subprocedure at specific
addresses, as given in the reference parameters. In other words, it can
change more than one value.
5.1 The subprocedure call
The syntax of the subprocedure call used in an algorithm is:
call NameOfSubProcedure (argument list)
Study the following subprocedure call:
call Calculations(number1, number2, sum, product)
display “The sum of ”, number1, “ and ”, number2, “ = ”, sum
display “The product of ”, number1, “ and ”, number2, “ = ”, product
Calculations is the name of the subprocedure, and number1 and number2 are
value parameters containing numeric values. These values may not be changed
by the subprocedure because they are displayed in the succeeding statements.
sum and product are two reference parameters. They contain addresses of
variables. The values in these specific addresses may be changed.
Actually, we’re going to use the subprocedure to calculate two values – the
sum and the product of the two numbers.
5.2 The subprocedure
The syntax of the subprocedure header line used in the planning is:
Sub NameOfSubProcedure(parameter list)
Here’s the subprocedure header for the subprocedure call in the previous
paragraph:
Sub Calculations(valNo1, valNo2, refSum, refProduct)
Calculations is the name of the subprocedure, which is the same name used in
the subprocedure call.
valNo1 and valNo2 are value parameters containing the numeric values
sent from the subprocedure call. refSum and refProduct are two reference
parameters that contain the addresses of the sum and the product. These two
parameters will contain the answers, which will also be accessible from the
main module.
Ed 3 BPP 4th pgs.indb 193
2012/11/26 2:45 PM
194
•
BASIC PROGRAMMING PRINCIPLES
Here’s the entire subprocedure:
Sub Calculations(valNo1, valNo2, refSum, refProduct)
~ Calculate the sum and the product of 2 numbers
refSum = valNo1 + valNo2
refProduct = valNo1 * valNo2
End Sub
The subprocedure uses parameters to receive “copies” of the values of number1
and number2. refSum and refProduct contain the addresses of the area in
memory where the subprocedure must store the result of the calculation. The
calling module will also refer to these addresses and will therefore be able to
retrieve the answers. End Sub terminates the subprocedure.
A function or subprocedure can be called from a main procedure or from
any other function or subprocedure as can be seen in some of the examples.
5.3 Calling an independent subprocedure and using a
subprocedure
The examples that follow demonstrate how to do the planning and write
algorithms that use subprocedures to solve a problem.
Example 3
Danny invested an amount at the Save-a-Lot Bank, which must be entered at
the beginning of the algorithm. The monthly interest rate is also entered. The
algorithm must calculate and display the amount of interest earned as well as
the balance at the end of every month for the next 15 months. At the end of
the algorithm the total amount of interest must be displayed. This example
uses functions and subprocedures where possible. A monthly interest rate is
used to test the program, for example an annual interest rate of 10% = 0.83%
per month.
EarnInterest()
CalcNewValues()
DisplayResults()
AccSum()
Figure 4: Example 3 hierarchy chart
Ed 3 BPP 4th pgs.indb 194
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
•
195
Planning
Description
Type
Variable name
Amount
Real
amount
Interest rate
Real
rate
Amount
Real
amount
Monthly interest
Real
monInt
Total interest
Real
totInterest
Real
valRate
Real
refAmt
Real
refMonthInterest
Real
valMInterest
Real
refTInterest
Integer
valMonth
Real
valAmt
Real
valMInt
Main procedure (EarnInterest)
Input
Output
Subprocedure (CalcNewValues)
Copy of interest
Parameters
rate
Address of
amount
Address of
interest rate
Subprocedure (AccSum)
Copy of monthly
Parameters
interest
Address of total
interest amount
Subprocedure (DisplayResults)
Copy of month
Parameters
number
Copy of amount
Copy of monthly
interest amount
Table 5: Input and output variables for Example 3
Algorithm
Sub DisplayResults (valMonth, valAmt, valMInt)
display valMonth, “ ”, valAmt, “ ” , valMInt
End Sub
~ Display monthly values
Sub CalcNewValues (valRate, refAmt, refMonthInterest)
refMonthInterest = refAmt * valRate / 100
~ Calculate interest
refAmt = refAmt + refMonthInterest
~ increase amount
End Sub
Sub AccSum (valMInterest, refTInterest)
refTInterest = refTInterest + valMInterest
End Sub
Ed 3 BPP 4th pgs.indb 195
~ Accumulate interest total
2012/11/26 2:45 PM
196
•
BASIC PROGRAMMING PRINCIPLES
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
The better of two class
test marks
Examination
20%
15%
50%
Table 6: Assessments and weightings
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.
Ed 3 BPP 4th pgs.indb 196
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
•
197
CalFinalMarks()
CalcCTMark()
CalcValues()
DisplayResults()
Figure 5: Example 4 hierarchy chart
Planning
Description
Type
Variable name
Mark for test 1
Integer
test1
Mark for test 2
Mark for class
test 1
Mark for class
test 2
Exam mark
Integer
test2
Integer
clTest1
Integer
clTest2
Integer
exam
Integer
betterClassTest
Integer
vaClMark1
Integer
vaClMark2
Integer
betterMark
Main procedure (CalcFinalMark)
Input
Intermediate
Better class test
Output
None
Function (CalcClMark)
Copy of class test
Parameters
1 mark
Copy of class test
2 mark
Better class test
Output
mark
Ed 3 BPP 4th pgs.indb 197
2012/11/26 2:45 PM
198
•
BASIC PROGRAMMING PRINCIPLES
Subprocedure (CalcValues)
Parameters
Copy of test 1
Copy of test 2
Copy of better
class test
Copy of exam
mark
Intermediate
Final mark
Indication – pass
or fail
Subprocedure (DisplayResults)
Copy of final
Parameters
marks
Copy of result
message
Output
Final mark
Message
Integer
valTest1
Integer
valTest2
Integer
valClassTest
Integer
valExam
Real
final
String
message
Integer
valFinalMark
String
valMessage
Real
valFinalMark
String
valMessage
Table 7: Input and output variables for Example 4
Algorithm
Function CalcClMark (valClMark1, valClMark2)
if valClMark1 > valClMark2
betterMark = valClMark1
else
betterMark = valClMark2
endif
return betterMark
~ Function header
Sub CalcValues (valTest1, valTest2,valClassTest,valExam) ~ Subprocedure
final = valTest1 * 0.15 + valTest2 * 0.2 + valClassTest * 0.15 + valExam * 0.5
if final >= 50 then
message = “Pass”
else
message = “fail”
endif
call DisplayResults (final, message)
End Sub
Sub DisplayResults (valFinalMark, valMessage)
~ Subprocedure
display “The final mark of the student is “, valFinalMark
display “The result is “, valMessage
End Sub
Ed 3 BPP 4th pgs.indb 198
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
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)
call CalcValues (test1, test2, betterClassTest, Exam)
end
•
199
~ Function call
~ Call subprocedure
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.
5.4 Functions and subprocedures without parameters
It is possible that a function or subprocedure can be called without sending
it any parameters. For instance, a function can be called where a value must
be entered and validated until it is correct. When a correct value is entered, it
must be returned to the calling module.
Example 5
A function is called to enter the discount that applies to a product. The discount
may never be more than 25%.
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
Ed 3 BPP 4th pgs.indb 199
2012/11/26 2:45 PM
200
•
BASIC PROGRAMMING PRINCIPLES
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
Function CalcFunc (valK)
return ((valK * 2) mod 4)
Ed 3 BPP 4th pgs.indb 200
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
•
201
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.
Ed 3 BPP 4th pgs.indb 201
2012/11/26 2:45 PM
202
•
BASIC PROGRAMMING PRINCIPLES
Call two subprocedures: one to calculate how many passengers travel
to each of the regions and another to calculate the profit earned by
the owner. Display the taxi owner’s profit for the day on the screen.
4.3 Max Contractors has five employees, each of whom receive a weekly
wage. The basic wage is entered. An employee may also borrow
money from Max Contractors, in which case 25% of the loan is
subtracted from the employee’s weekly wage. If this amount is
more than R50, then R50 is subtracted. But if R50 is more than the
remainder of the loan amount, the remainder is subtracted. The loan
amount is also entered. The program must display the amount the
employee will receive as well as the remaining amount of the loan.
These answers must be calculated in a subprocedure.
4.4 Do the planning and write an algorithm to solve the following
problem.
At the Cheap Unfair Store, salaries for employees are computed as
follows: A male employee earns a basic salary of R2 500 per month.
He receives an additional R250 for every year of experience. He
also receives an additional R550 if he has a qualification. Males pay
10% tax and 8% to the pension fund, which are deducted from the
gross salary to produce the net salary. Female employees earn a
basic salary of R2 000 per month and an additional R200 for every
year of experience. Females receive an additional R450 if they have
a qualification and they pay 9.5% tax and 7.5% to the pension fund.
Enter the gender, years of experience and whether the person has a
qualification. Call a separate function for females and males, each of
which must return the gross monthly salary. Then call a procedure
to calculate the tax amount and pension fund amount. Call another
function to return the net salary for this person. Display the gross
and net salaries in the main module. You can assume that the input
values will be valid.
4.5 The admission requirements to study IT at the ABC University are as
follows:
• Admission into the general first year (mainstream students):
• An APS score of 18 and at least 3 for English and 4 for
Mathematics
• Admission into the IT Foundation programme:
• An APS score of 18 and at least 3 for English and Mathematics or
• an APS score of 20 with at least 5 for Maths Literacy and 3 for
English
• The APS score is calculated by adding the scores for the best 6
subjects together, excluding the score for Life Skills and any score
of 2 or less.
Ed 3 BPP 4th pgs.indb 202
2012/11/26 2:45 PM
FUNCTION PROCEDURES AND SUBPROCEDURES
Example 1
•
203
Example 2
English
3
English
4
Ndebele
3
Northern Sotho
3
Mathematics
4
Maths Literacy
5
Biology
4
Physical Science
2
Life Orientation
Technical
Drawing
Business Studies
5
Art
3
4
Life Orientation
6
4
Accounting
4
APS
22
APS
19
Table 8: Two examples of APS scores
The person in Example 1 will qualify to enter directly into the main
stream in the general first year, but the person in Example 2 won’t be
considered for either the general first year or the foundation course.
Write an algorithm with function procedures and subprocedures to
indicate to prospective students whether they qualify for the IT course,
the IT foundation course, or neither.
The main procedure must ask the user to enter the following fields:
• Reference number of prospective student
• Initials and surname of prospective student
• Mark for English
• Mark for Second Language
• An indication whether the prospective student has Mathematics,
Maths Literacy or neither of these subjects. If the student has
either Maths or Maths Literacy, their mark must be entered. If the
student doesn’t have either Maths or Maths Literacy, a suitable
message rejecting the application must be displayed and the
program must not continue with the student’s application.
Call a function procedure to determine and return the APS score
for the student. The three marks already entered must be sent to the
function procedure as value parameters and the marks for the next
three best subjects (excluding Life Orientation) must be entered in the
function. The APS score must then be determined and returned.
If the student has Mathematics, call a subprocedure to determine
whether the student qualifies for the general first year, foundation year
or does not qualify at all. Decide on your own parameters and types.
If the student has Maths Literacy, call a function procedure to
determine whether the student qualifies for the foundation programme.
Ed 3 BPP 4th pgs.indb 203
2012/11/26 2:45 PM
204
•
BASIC PROGRAMMING PRINCIPLES
Display a suitable message about the application status of the
prospective student. The message should include the student name,
reference number and APS score. If not accepted, the reason should
be provided.
4.6 You are the bookkeeper for a retail company that bought stock
from 25 suppliers during the past month. The amount paid to the
suppliers included 14% VAT. To determine the selling price you
increase the cost price of the stock by 37.5%.
Do the planning and then write an algorithm to display a report of
the amounts paid to the various suppliers. Also display how much the
company must pay to the Receiver of Revenue (SARS). The algorithm
must contain the following:
• All input is done in the main procedure.
• A subprocedure must divide the amount payable to each supplier
into the basic amount and the VAT amount.
• A function must display the basic amount and the VAT amount
for every supplier.
• A function must calculate the selling price (selling value) for the
goods received from each supplier.
• The first subprocedure must also divide the selling value into the
basic amount and the VAT.
• A function must receive the VAT amount on the cost price, the
VAT amount on the selling price, and a total for the VAT payable
to SARS. It will calculate the difference between the VAT amounts
and accumulate these differences for the 25 orders in the VAT
total.
• The total amount that must be paid to SARS must be displayed in
a function at the end of the algorithm.
Ed 3 BPP 4th pgs.indb 204
2012/11/26 2:45 PM
205
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.
Ed 3 BPP 4th pgs.indb 205
2012/11/26 2:45 PM
206
•
BASIC PROGRAMMING PRINCIPLES
1 Input and output files
The difference between input and output files is based on the way these files
are used and accessed.
An input file contains stored data that can be specified as input to a
program when read from the file during processing.
An output file is used by a program to store new data, by writing it to the
file. When dealing with sequential files, a “new” file is always used because the
changed or newly created data must be written or rewritten from the first to
the last line of text.
The file pointer will indicate the position in the file where text must be
read or written.
It is not possible to write data to a specific position within existing data in
an input file, but more data can be added after the existing data. This is called
appending data.
Every file is identified by an external file name, such as marks.txt and
profit.txt.
2 Opening a sequential access file
Every file that is used in the program must be opened before it can be used.
The open statement, which contains the name of the file, will try to find the
specified file. When the file is found, it will connect this external physical text
file to the filename used in the program in order to use it in the program.
As discussed in the previous paragraph, there are input files, output files
and output files to append data to. The programmer has to specify in the open
statement what type of file must be opened.
In the generic programming (where we do the planning) the following
open statements will be used:
Input file
Example:
open input(name of file)
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)
Ed 3 BPP 4th pgs.indb 206
2012/11/26 2:45 PM
SEQUENTIAL TEXT FILES
•
207
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.
if exists (name of file) then
open the file
endif
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
3 Closing a sequential access file
A file should be closed as soon as possible to prevent loss of information. In the
case of an input file, it must be closed as soon as all the text has been read from
it and, when using an output file, as soon as all the text has been written to it.
In cases where quite a number of files are used at different stages in the
program, it is very important to adhere to this rule by keeping open only the
files that are in use. It is also essential that files are opened just before their data
is needed, and not before.
In the planning of a program, the statement used to close a file is:
close(name of file)
Example: close(employees.txt)
Ed 3 BPP 4th pgs.indb 207
2012/11/26 2:45 PM
208
•
BASIC PROGRAMMING PRINCIPLES
4 Reading information from a sequential access
file
As mentioned earlier, a sequential access file is always read from the beginning
of the file. The open statement positions the pointer before the first character
of text.
The read statement enables the program to read one line of text at a time,
until the newline character is found. However, the string that is returned when
the line is read doesn’t contain the newline character.
Lines can be read from a file until the end-of-file (eof) character is found,
which indicates that the file doesn’t contain any data that has not been read.
The statement in an algorithm to read a line of text from a file is:
read(name of file)
The line of text is normally placed into a string variable from where it can
be used for further processing.
Example:
EmployeeData = read(employees.txt)
In an algorithm, the word eof indicates that the end of the file has been
encountered, so processing must stop and the file must be closed.
Example 1
In this pseudocode example, lines of text are read from the employee file.
Every line of text is then displayed. The process is repeated until the end of the
file is reached.
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.
Ed 3 BPP 4th pgs.indb 208
2012/11/26 2:45 PM
SEQUENTIAL TEXT FILES
•
209
The statement EmployeeData = read(employees.txt) took a complete
record from the file and read it into the variable called EmployeeData. This
line of text can consist of many different fields separated by special characters,
called delimiters. String manipulation statements would first be necessary to
divide the line of text into different variables before the individual values can
be used.
The records in the file could be:
12345*Boyd.R.S.*Sales*Manager#
23456*Nkosi.S.A.*Purchases*Assistant#
33445*Pillay.N.*HR*Assistant#
41231*Mokoetsi.M.M.*Marketing*Officer#
:
:
The record EmployeeData contains four fields – the employee number
(empNum), employee name (empName), department (empDept) and the job
description (empJob).
After the first record has been read, the variable EmployeeData will have
the value “12345*Boyd.R.S.*Sales*Manager#”. We would then want to get the
employee number, employee name, department and job description separately.
It can be clearly seen that fields are separated by an asterisk and that a hash
sign indicates the end of the record.
Various string manipulation statements exist in different programming
languages to find the position of the first “*” in the string. The substring up to
that position can then be placed in the variable called empNum resulting in
empNum = 12345. These values can then be deleted from the beginning of the
original string up to the point of the first delimiter. The string now contains the
value “Boyd.R.S.*Sales*Manager#”. The process can be repeated to place the
value “Boyd.R.S.” into empName and the value “Sales” into empDept. Lastly,
the value “Manager” will be placed into empJob and when the # is encountered
as a delimiter, the process will stop for the current record.
This string manipulation process enables the programmer to have access
to the individual variables empNum, empName, empDept and empJob. The
programmer can now use them in processing e.g. to display them on the screen
of the computer.
The string manipulation and division into separate variables could typically
be done in a subprogram and the hierarchy chart is provided. The algorithm
for the main modules is also provided – you can see that it is a modification of
the previous algorithm.
Ed 3 BPP 4th pgs.indb 209
2012/11/26 2:45 PM
210
•
BASIC PROGRAMMING PRINCIPLES
MainModule()
DisplayHeadings()
GetFields()
Figure 1: Hierarchy chart for MainModule algorithm
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.
The output for this piece of code could be as follows:
EMP NUMBER
EMP NAME
DEPARTMENT JOB DESCRIPTION
12345
23456
33445
41231
:
:
Boyd.R.S.
Nkosi.S.A.
Pillay.N.
Mokoetsi.M.M.
Sales
Purchases
HR
Marketing
Ed 3 BPP 4th pgs.indb 210
Manager
Assistant
Assistant
Officer
2012/11/26 2:45 PM
SEQUENTIAL TEXT FILES
•
211
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
1.5 It is impossible to modify existing values in a text file.
1.6 The data in a sequential access file is always accessed in consecutive
order from the beginning of the file to the end.
2. Provide a hierarchy chart and an algorithm for each of the following. It
is not necessary to include the code for the sub procedures where string
functions are used to break each line into positions in the array.
2.1 A file called “diary.txt” contains first names, surnames, e-mail
addresses and telephone numbers for 100 people in the following
format:
Freddy,Gomes,GomesF@gmail.com,0824154433.
Some of the e-mail addresses and telephone numbers need to be
changed.
You can assume that the file already exists and that there will be
exactly 100 text lines in the file.
2.2 The file C:\Employee.txt contains a text line containing the following
information for each employee in a company:
Employee number
Name
Gender
Department code
Annual salary
Values are separated by dollar ($) signs and the end of each line is
indicated by an at (@) sign.
All the employees in Department A received a 6.5% increase. Update
the salary for each of these employees.
Ed 3 BPP 4th pgs.indb 211
2012/11/26 2:45 PM
212
•
BASIC PROGRAMMING PRINCIPLES
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.
5 Writing information to a sequential access file
As mentioned earlier, text lines can be added to an existing file or a new output
file can be created. The open statement indicates the way to write to the file.
In both cases, the write statement enables the program to write one line of
text at a time. The new line character (indicating the end of a record) will not
automatically be written to the file, so when the programmer wants the next
string of text to be written on a new line it must be specified.
Lines of text are usually also written in a loop, so when the end is reached
the programmer can simply close the file.
The statement in an algorithm to write a line of text to a file is:
write(name of file)
The line of text is normally written from a string variable. This can be
indicated in an algorithm by specifying the word from followed by the variable
name.
Example:
write(employees.txt) from EmployeeData
In an algorithm, an additional write statement must be included if the new
line character must also be written. If it need not be written, this additional
write statement can be ignored:
write new line
Ed 3 BPP 4th pgs.indb 212
2012/11/26 2:45 PM
SEQUENTIAL TEXT FILES
•
213
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:
Concatenate
Ed 3 BPP 4th pgs.indb 213
empNum, “*”, empName, “*”, empDept, “*”, empJob,
“#”into EmployeeData
2012/11/26 2:45 PM
214
•
BASIC PROGRAMMING PRINCIPLES
Our algorithm could be changed, as follows:
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)
The file will be created containing the following records:
12345*Boyd.R.S.*Sales*Manager#
23456*Nkosi.S.A.*Purchases*Assistant#
33445*Pillay.N.*HR*Assistant#
41231*Mokoetsi.M.M.*Marketing*Officer#
:
:
6 Reading from and writing to the same
sequential file
If lines in a sequential file need to be modified, the only way to do this is to
read all the records into an array, manipulate the array elements, then write the
array back to the file by recreating the file.
Example 3
Let’s say we need to change either the job description or department of
particular employees.
Initial planning
Step 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
Ed 3 BPP 4th pgs.indb 214
2012/11/26 2:45 PM
SEQUENTIAL TEXT FILES
•
215
Ask if department must be changed
If job description must be changed
Accept new job description
Replace existing job description in the array for the employee data
that needs to be changed
If department must be changed
Accept new department name
Replace existing department in the array for the employee that
needs to be changed
Step 3: Create a new file from the array
MainModule()
ReadFileIntoArray()
GetFields()
UpdateRecords()
CreateFileFromArray()
UpdateArrayElement()
Figure 2: Hierarchy chart for Example 3
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
Ed 3 BPP 4th pgs.indb 215
2012/11/26 2:45 PM
216
•
BASIC PROGRAMMING PRINCIPLES
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
Ed 3 BPP 4th pgs.indb 216
2012/11/26 2:45 PM
SEQUENTIAL TEXT FILES
•
217
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
Ed 3 BPP 4th pgs.indb 217
2012/11/26 2:45 PM
218
Chapter 11
Introduction to objectoriented programming
Introduction
The art of software development is one of the most difficult challenges
undertaken by humankind. To complicate matters, computer hardware is
constantly being improved in terms of speed and capacity.
The more hardware enables us to do, the more we want it to do, so the more
complex problems and software solutions become.
It is because of this complexity that we are constantly looking for new
strategies to simplify the software development process. Object orientation is
such a strategy. The object-oriented approach is a different way of thinking
about computation and problem solving. People often use this form of thinking
to address problems in everyday life, which makes object orientation a natural
approach to problem solving and easy to grasp.
In the procedural approach to problem solving, we focused on processes
and procedures. In the object-oriented, or OO, world, we focus on the data, its
properties or attributes, and responsibilities, and how it interacts with other
parts of the system. As a result, information is structured differently within
the computer.
A system developed using the object-oriented approach typically consists
of a collection of objects that communicate with one another to solve a
problem. You could say that object-oriented systems are defined using objects.
One of the great advantages of the object-oriented approach is that it makes
it easy to re-use objects. We’ll discuss re-use in more detail later in this chapter.
Some programming languages that use object orientation are:
• C++
• Delphi
• Smalltalk
• Java
Ed 3 BPP 4th pgs.indb 218
2012/11/26 2:45 PM
INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
•
219
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.
(Data)
Properties
Operations
Figure 1: An object with properties and operations
Ed 3 BPP 4th pgs.indb 219
2012/11/26 2:45 PM
220
•
BASIC PROGRAMMING PRINCIPLES
For example, consider a motor car object. Typical attributes for such an object
might be fuel consumption, speed, power and engine size. Possible operations
might be stop, accelerate, change gears and reverse. Typically, the speed of the
motor car is not modified directly, but will be modified by, for example, the
accelerate operation. The accelerate operation, in turn, will modify the speed
data, or value of the speed attribute. From this it is clear that we use operations
primarily to change the data of an object.
All the objects we’ve considered so far contain tangible things. However,
there are other kinds of objects in the real world that aren’t tangible, such
as roles, incidents and interactions. For example, roles can include lecturer,
student and pilot; cycle race or political meeting would be an incident; and
interview and conversation would be interactions.
Table 1 shows examples of the characteristics of an object.
Characteristics
Examples
Are abstractions, concepts or things
Human being
Human being knows his or her
physical capabilities
References to use for species
Have clear boundaries
Are found in the problem domain
Know things about themselves
Interact with other objects
Height, weight
Interact with other humans and
things
Table 1: Characteristics of the object human being
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.
Ed 3 BPP 4th pgs.indb 220
2012/11/26 2:45 PM
INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
•
221
Table 2 shows some of the properties, both private and public, of the object
called Bob.
Property Name
Scope
Type
Value
Name
Public
String
Bob
Age
Private
Integer
23
Gender
Private
String
Male
Weight
Private
Integer
82
Height
Private
Real
1.86
Table 2: Properties of 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.
Ed 3 BPP 4th pgs.indb 221
2012/11/26 2:45 PM
222
•
BASIC PROGRAMMING PRINCIPLES
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
Object: Car
Object: Car
Attribute Name
Type
Attribute Name
Type
Type
Passenger
Type
Passenger
Make
Audi
Make
VW
Model
A4
Model
Polo
Colour
Blue
Colour
White
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.
2 Encapsulation and information hiding
In the object-oriented approach, classes, and therefore also objects of that class,
are similar to black boxes with a clearly defined interface. This interface is the
only mechanism that other objects can use to communicate with the object.
We say that inside a class, behind the interface, the data and the
implementation of the operations are encapsulated or enclosed in a capsule.
Ed 3 BPP 4th pgs.indb 222
2012/11/26 2:45 PM
INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
•
223
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
and operations
Message from another object
Implementation
Private attributes
and operations
Figure 2: An object receives a message from another object
We hide information within a class by making some properties and operations
private. We make only the properties and operations that can be manipulated
by other classes public. The collection of these public attributes and operations
forms the interface of a class. Because other parts of the system can interact
with an object only through its interface, the other parts of a system cannot
accidentally change private property values in an object. This means that
information hiding makes objects more robust.
By hiding information we can change the implementation of a class
without affecting other classes that rely on it. We achieve this by not changing
the interface on which other classes rely. The opposite is also true. Changes to
other parts of a system will not affect the internal workings of this class. As a
result, information hiding ensures the independence of classes and objects.
Because information hiding makes objects more robust and independent,
they are easily re-used in the object-oriented approach. Once we have defined
a class, we can re-use it, or instantiate it, in other parts of a system, and even
in other systems. The independence of classes also reduces the impact when
we have to make corrections and changes to a system. As a result, the cost of
corrections and changes tends to be lower.
Consider a class called Sorter, which sorts a list of integers. The interface
of the Sorter class consists of one operation named Sort. Sort accepts a list
of integers as a parameter.
Ed 3 BPP 4th pgs.indb 223
2012/11/26 2:45 PM
224
•
BASIC PROGRAMMING PRINCIPLES
Class: Sorter
Attributes
Operations
Public Sort (pIntegerList : Array of integers)
Table 4: The class called Sorter
Now suppose the Sort operation (method) uses the bubble sort algorithm
to sort the list of integers. This doesn’t work well, so the programmer has to
change it to use the quick sort algorithm. To make the change, the programmer
only has to re-write the Sort operation. The interface stays exactly the same,
so the classes whose objects use objects in the Sorter class don’t need to be
changed.
3 Design notations
Three people who have done a lot of work in the OO design notation area
are James Rumbaugh, Grady Booch and Ivar Jacobson. At first, each of them
had their own method of representing an OO design. Not only were the
representations different, the underlying theories of object behaviour and
interaction were also different. A couple of years ago, Rumbaugh, Booch and
Jacobson conceived of the Unified Modelling Language, or UML. UML enables
the designer to represent classes, with their attributes and operations, as well as
the relationships between classes.
4 Relationships between classes
The relationships between classes fall into three categories:
• association,
• aggregation, and
• inheritance.
Let’s consider each of these categories.
Ed 3 BPP 4th pgs.indb 224
2012/11/26 2:45 PM
INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
•
225
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.
Employee
Uses
Company
Figure 3: The association between Employee and Company classes
4.2 Aggregation
An aggregation is a specific form of association, and is not an independent
relationship. In an aggregation, one class is part of another class. This type of
relationship is often referred to as a “part-of ” relationship. Note that the class
that is a part of another class can exist only as part of the container class, so it
cannot exist independently. Note also that, like association, aggregation works
at the class level not the object level.
Consider a car, which consists of a body, wheels, windows, and so on.
There are thus relationships between the motor car and its components. More
specifically, an aggregation relationship exists between the car class and the
body, wheel and window classes.
Figure 4 shows an example of an aggregation.
Ed 3 BPP 4th pgs.indb 225
2012/11/26 2:45 PM
226
•
BASIC PROGRAMMING PRINCIPLES
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().
Ed 3 BPP 4th pgs.indb 226
2012/11/26 2:45 PM
INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
•
227
Inheritance is a type of relationship that we often refer to as a “kind-of ”
relationship. It is another aspect of the object-oriented approach that allows us
to improve re-use. In the vehicle example, if we want to create a bus class,
we can create it as another subclass of the vehicle class. This means that all
the properties and operations defined in the vehicle class are automatically
defined in the bus class. All that remains is to define the properties and
operations specific to the bus class.
Vehicle
Fuel_consumption
Speed
Power
Engine_Size
Number_of_Wheels
Properties
Stop()
Accelerate()
Change gears()
Operations
Motorbike
Stroke
Truck
Max_Load
Car
Max_Passengers
Load()
Unload()
Figure 5: Inheritance between a super class and subclasses
It is also possible for a subclass to inherit from more than one super class. This
is referred to as multiple inheritance. Not all programming languages support
multiple inheritance. When you use the object-oriented approach to solve a
problem, use inheritance, and especially multiple inheritance, sparingly, as
the relationships can become quite complex.
5 More concepts
This chapter is a basic introduction to OO, but you should know that there are
some advanced concepts that we have not covered here. These include abstract
classes, polymorphism, overriding and overloading.
Ed 3 BPP 4th pgs.indb 227
2012/11/26 2:45 PM
228
•
BASIC PROGRAMMING PRINCIPLES
6 Designing an object-oriented solution
The object-oriented approach is about far more than just a couple of new
programming structures and techniques. As we mentioned before, it’s a
whole new way of thinking. This means that objects are not only part of the
programming of a system but are used right from the start during the analysis
and design phases.
Here are some basic steps to follow when solving a problem using the OO
approach:
1. Read the problem statement and identify classes.
2. Look for properties and methods that apply to the classes identified.
3. Determine the relationship and interaction between classes.
4. Design the algorithms for the methods using structured design.
5. Develop the main algorithm.
You can see that the whole approach to designing a system is different. Now
try some problems.
Exercises
1. Explain the difference between a class and an object.
2. List some of the advantages of object orientation.
3. Assume we have a class called dog. Name three possible attributes and
three possible operations for this class.
4. Assume we have a class called bicycle. Name four possible attributes
and three possible operations for this class.
5. A retail company needs an ordering system to keep a record of orders
per customer. For each customer, there is a delivery address, which
has to be maintained. Each order consists of order line items. For an
order line item, the company needs the item code and quantity that the
customer ordered. Identify classes for this problem. Define attributes and
operations for each of the classes you identify.
6. A soccer club requires a system that can be used to keep track of its teams
and the players in each team. Currently the club has four teams, A, B, C
and D. The club needs basic information on each player, such as first name,
surname, age, date of birth, weight, height and the position in which they
play. The club needs to be able to change a player’s position, add a player to
or remove a player from a team, and assign a team to a match.
For each team, the club wants to know the number of games played and
the number of games won. In addition, the club wants to keep track of
matches, where they are played, which teams play which matches and
when they play them.
Identify classes for this problem. Define properties and operations for each of
the classes you identified. Then identify relationships between the classes.
Ed 3 BPP 4th pgs.indb 228
2012/11/26 2:45 PM
229
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
Ed 3 BPP 4th pgs.indb 229
2012/11/26 2:45 PM
230
•
BASIC PROGRAMMING PRINCIPLES
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.
Ed 3 BPP 4th pgs.indb 230
2012/11/26 2:45 PM
T OOLS FOR PLANNING PROGRAMS
•
231
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.
Table 1: Flowchart symbols
Ed 3 BPP 4th pgs.indb 231
2012/11/26 2:45 PM
232
•
BASIC PROGRAMMING PRINCIPLES
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
num1 >
num2?
“num2 is
bigger than
num1”
True
“num1 is
bigger than
num2”
End
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.
Ed 3 BPP 4th pgs.indb 232
2012/11/26 2:45 PM
T OOLS FOR PLANNING PROGRAMS
•
233
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
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.
Ed 3 BPP 4th pgs.indb 233
2012/11/26 2:45 PM
234
•
BASIC PROGRAMMING PRINCIPLES
Symbols used to construct a Nassi-Shneiderman
diagram
Process block
A process block represents the simplest of steps. When a process block
is encountered, the statements within the block are processed. When the
statements have been processed, processing proceeds to the next block.
Decision block
This block enables the programmer to include a condition in the diagram,
which will produce different branches or paths for true and false processing.
Iteration block
An iteration block allows the programmer to repeat a block of instructions a
number of times while a specific condition is true or until a specific condition
is true.
Now we’ll draw Nassi-Shneiderman diagrams to solve our two problems:
Example 1
Draw a Nassi-Shneiderman diagram to enter two numbers that are not equal,
and display the bigger number.
FindTheBigger
display “Enter a number”
enter num1
display “Enter the next number – not equal to the first number”
enter num2
num1 > num2?
True
False
display “num2 is bigger than num1”
display “num1 is bigger than num2”
end
Figure 3: Nassi-Shneiderman diagram for Example 1
Ed 3 BPP 4th pgs.indb 234
2012/11/26 2:45 PM
T OOLS FOR PLANNING PROGRAMS
•
235
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
Figure 4: Nassi-Shneiderman diagram for Example 2
Ed 3 BPP 4th pgs.indb 235
2012/11/26 2:45 PM
236
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.
Ed 3 BPP 4th pgs.indb 236
2012/11/26 2:45 PM
ERROR HANDLING AND DEBUGGING TECHNIQUES
•
237
Computer programs are written in programming languages, each of which
has specific rules that must be taken into consideration. Even though we’re
only doing generic work by planning programs, we also have to adhere to
specific rules, for instance spelling the name of a variable exactly the same
throughout an algorithm.
1.2 Logical errors
Logical errors can sometimes be very difficult to correct. In everyday life it
is not possible to leave your house before you’re dressed. This is not a logical
way to behave! Here’s a very simple example of a logical error in an algorithm.
This algorithm contains an instruction that asks the computer to add a
variable called number to another variable called total. But the programmer has
forgotten to ensure that the variable number has a valid value! The instructions
could have been the following:
total = total + number
enter number
These two instructions are in the wrong order!
1.3 Data errors
Data errors are usually found in the input data. We have repeatedly tested
input data in our examples to ensure that valid values have been entered. For
instance, does the variable contain a numeric value, did the user enter a valid
character, and so on. Error messages were displayed whenever incorrect data
was entered, and often the user was asked to re-enter the data until valid data
was entered.
2 Trace tables
A trace table can be used to test the correctness of a program. There may be
only a small error that isn’t obvious. However, when a program is carefully
checked, the chances are very good that the output will be correct. Trace tables
were explained in earlier chapters, but are repeated here. Let’s use an example
to illustrate this concept.
Write an algorithm to calculate the product of two integers, the variables
num1 and num2. Store the answer in the variable product.
Ed 3 BPP 4th pgs.indb 237
2012/11/26 2:45 PM
238
•
BASIC PROGRAMMING PRINCIPLES
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
To create a trace table we need an instruction column, a column for each of
the variables and a column for the output (which will be shown on the screen).
The instructions will be written in the first column in the same sequence
as in the program.
To test the program, we’ll use num1 = 4 and num2 = 5.
Instruction
num1
num2
product
display
enter
4
Enter the
second
integer
display
enter
Output
Enter the first
integer
5
calculate
display
20
The product
is 20
Table 1: The trace table for CalcProduct
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.
Ed 3 BPP 4th pgs.indb 238
2012/11/26 2:45 PM
ERROR HANDLING AND DEBUGGING TECHNIQUES
•
239
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.
Instruction
noTickets
amtDue
Outcome
of If
How many
tickets do
you want to
buy?
display
enter
20
if
False
if
False
calculate
Output
500
display
The amount
due for 20
tickets is
R500
Table 2: The trace table for BuyTickets
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.
Ed 3 BPP 4th pgs.indb 239
2012/11/26 2:45 PM
240
•
BASIC PROGRAMMING PRINCIPLES
The correct algorithm will now be:
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.
1. Enter the temperature in degrees Fahrenheit (F) and convert it to degrees
Celsius (C) using the following formula:
9C = 5(F – 32)
Display the temperature in Fahrenheit and Celsius. Test the algorithm
using 32 °F and 212 °F. The answers should be 0 °C and 100 °C.
2. Enter two numbers. If the numbers are equal, increase the sum of the
two numbers by 20%, but if the first number is less than the second
number, calculate the difference between the two numbers. If the first
number is greater than the second number, decrease the product of the
two numbers by 25%. In each case, store the answer in a variable called
answer. Display the value of answer on the screen. Test the algorithm
using the numbers 12 and 5, 4 and 8, and 7 and 7.
In each case, calculate the answers beforehand to ensure that your algorithm
produces the correct answers.
Ed 3 BPP 4th pgs.indb 240
2012/11/26 2:45 PM
GLOSSARY
•
241
Glossary
Accumulation
Accumulation is used in problem solving to
calculate a total or an average. When you
add 1 to the accumulator during every
execution of the loop, the accumulator is
called a counter.
Accumulator
A variable that acts as a register to store the
results of an accumulation process.
Aggregation
In terms of the relationships between object
classes, aggregation occurs when one class
is part of another class.
Algorithm
A set of instructions written in a specific
sequence to solve a problem.
Argument list
The list of variables in the call statement that
correspond to the list of parameters in the
function or subprocedure.
Array
Variables of the same data type grouped
under a single name.
Array element
A single variable in an array that can contain
a value at a given time.
Association
An expression of the relationship between
two object classes.
Boolean variable
A variable that can take only one value, true
or false.
Bubble sort
A sorting method in which elements in an
array are compared to each other in pairs;
when an element is not in sequence, it
trades places with the other element until
all elements are sorted in the required
sequence.
Ed 3 BPP 4th pgs.indb 241
Character
A single number, letter or special character;
any one stroke that can be typed on a
keyboard.
Character variable
A variable that contains a single letter,
number or special character,
Compound If statement
A statement used to test more than one
condition before the result can be
evaluated to be either true or false.
Class
A construct used as a template to create
objects that have predefined properties.
Constant
A fixed value that cannot change throughout
the entire program; may be any data type.
Data
A collection of facts, such as values,
measurements, or readings.
Database
A number of related files or tables.
Data errors
Incorrect data that causes a program to cease
processing or provide incorrect results.
Data processing
A sequence of operations performed on data
to generate information.
Data validation
A test to check that input data can be used by
the program in its current format.
Data warehouse
The largest structure used to collect and store
data for processing, analysis and reporting;
may consist of several databases.
Encapsulation
Also known as information hiding, a
technique that makes the internal workings
of a class invisible to all other classes.
2012/11/26 2:45 PM
242
•
BASIC PROGRAMMING PRINCIPLES
End-of-file character
A character used to signal that the file doesn’t
contain any data that has not been read.
Field
Also known as a data item, a field is a
number of characters or a name.
File
A collection of related records organised and
stored in a specific way.
File pointer
Indicates the position in the file where text
must be read or written.
For loop
Also known as a fixed count loop or an
automatic count loop, a statement used
when the number of iterations of a set of
instructions is known.
For-next loop
Used to repeat a section of code a number
of times with a control variable that has a
differing value each time through the loop.
Function call
A statement that activates or calls a function
from another part of the algorithm.
Function header
The first line of a function, which contains
the word function, a function name and a
possible list of parameters.
Function procedure
Instructions that perform a specific task that
is often repeated are coded separately so
that they can be reused whenever required.
Hierarchy chart
A diagram that provides a global view of the
modules in a program, showing how they
link together to function as a complete
program.
If statement
An instruction that controls program flow by
allowing a section of code to execute only
when a specified condition is true.
If-then-else statement
An If statement that specifies two actions:
one action to take when the specified
condition is true and another action to
take when the condition is not true.
Index
Also known as a subscript, an indicator of the
position of an element in an array.
Ed 3 BPP 4th pgs.indb 242
Information
The result of data processing.
Inheritance
As a relationship between object classes,
the passing of characteristics from super
classes to sub classes.
Input
The data entered into a system for processing
into output.
Input file
Stored data that can be specified as input to
a program when read from the file during
processing.
Integer variable
A variable that contains a whole number
that has no fractional or decimal part; the
number can be positive, negative or zero.
Intermediate variables
Variables used in a solution to help with the
calculations.
IPO chart
An Input/Processing/Output (IPO) chart,
which enables programmers to do
comprehensive planning; the Input and
Output columns contain only variable
names, and the Processing column
provides an overview of the steps.
Iteration
Also known as looping, a type of
programming used when sets of
instructions are repeated a number of
times.
Logical error
An error resulting from faulty reasoning;
a bug in a program that causes it to
terminate abnormally or to produce
incorrect output.
Logical operator
An operator that joins two Boolean
expressions to yield a Boolean result, either
true or false.
Modularisation
The division of a program into smaller pieces
called modules to improve flexibility and
shorten development time.
Nested If statement
One or more If statements contained within
another If statement.
Nested loop
A loop contained within another loop.
2012/11/26 2:45 PM
GLOSSARY
New line character
The new line character indicates the end of a
record in a file.
Object
A container for data, with attributes, and the
operations needed to manipulate that data.
One-dimensional array
The simplest form of an array, consisting of
one column of elements.
Operator
A symbol used in an expression or equation,
which tells the computer how to process
the data.
Output
The result of processing input data.
Output file
A file used by a program to store new data by
writing to the file.
Parallel arrays
Two or more arrays that are related to one
another and have the same number of
elements.
Parameter
Data in the form of variables or values that
is sent to a function or a sub procedure
so that it can perform the task it has to
do.When dealing with a subprocedure, a
parameter may also contain the address in
memory to obtain and manipulate a value.
Post-test loop
A Do-while loop in which the statements in
the body of the loop are processed at least
once, and the condition is tested only after
the statements in the body of the loop
have been processed.
Pretest loop
A Do-until loop in which the condition is
tested before the statements in the body of
loop are processed.
Private scope
An object property that is visible only inside
the object it applies to.
Properties
The attributes of an object, each of which has
a scope, a type and a value.
Pseudocode
The way in which algorithm steps are written
so that they can be followed easily and
understood.
Ed 3 BPP 4th pgs.indb 243
•
243
Public scope
A object property that visible within the
object it applies to as well as to other
objects within the same system.
Real number
A variable that contains a positive or negative
number with a decimal part.
Record
A group of related fields.
Reference parameter
A parameter that is passed by reference to a
location in memory.
Relational operator
The operator used in a comparison between
two values, the outcome of which is always
a Boolean value.
Select case
Structures used to perform processing steps
depending on the outcome of a tested
condition, in which the same variable is
tested for many different values.
Selection sort
An array sort method that selects the smallest
value from the array and exchanges it with
the first element in the array, after which
the second smallest element is selected
from the array and exchanged with the
second element; a process that continues
until the entire array is in a pre-specified
order.
Sentinel
A value that is not a legitimate data value and
is used to terminate a loop.
Sequential access file
Also known as a text file, a file in which
the characters and fields are stored in
sequential order, one record after another.
String
A variable consisting of two or more
alphanumeric characters.
Subprocedure
A separate procedure that consists of lines
of code to solve a specific part of a larger
problem.
Subprocedure call
A statement that activates or calls a
subprocedure.
2012/11/26 2:45 PM
244
•
BASIC PROGRAMMING PRINCIPLES
Subprocedure header
The first line of a subprocedure, which
contains the word subprocedure, the
subprocedure name and a possible list of
parameters.
Syntax error
An error in the grammar of a statement.
Table
A structure made up of rows and columns, in
which each row represents the data of one
entity and each column contains a category
of data.
Trace table
Also known as desk checking or a
walkthrough table, a method of testing the
logic of an algorithm normally done prior
to writing it in a programming language.
Two-dimensional array
An array consisting of a number of rows and
a number of columns.
Value parameter
A copy of the value is passed to the function
or subprocedure as a parameter.
Bibliography
Erasmus HG, Fourie M & Pretorius CM 2002. Basic programming principles. Sandton:
Heinemann.
Farrell J 2002. Programming logic and design introductory. (2nd edn) Boston:
Thomson Course Technology.
Farrell J 2007. Programming logic and design comprehensive. (4th edn) Boston:
Thomson Course Technology.
Farrell ME 2005. Learning computer programming: It’s not about languages. Hingham:
Thomson Delmar Learning.
Robertson LA 2004. Simple program design. (4th edn) Boston: Thomson Course Technology.
Spranckle M 1992. Problem solving and programming concepts. Hillsdale: Prentice Hall
International.
Vickers, P 2008. How to think like a programmer (problem solving for the bewildered). London:
Cengage Learning.
Ed 3 BPP 4th pgs.indb 244
2012/11/26 2:45 PM
INDEX
•
245
Index
Entries are listed in letter-by-letter
alphabetical order.
A
accumulator 115
aggregation 225–226
algorithm 19, 20
calculations 46–48
examples 29
phases 23
steps 33–36, 39
testing 36–45
writing 29
alternative problem solutions 25
analysis, problem 24–25
argument list 184
arithmetic equations 10–11, 13
arithmetic expressions 9–10
arithmetic operators 11–13, 53
array name 154
array properties 154–155
arrays 153
assignment statement 13–14, 184
assignment symbol 8
association 225
B
Boolean value 6, 53, 54
brackets 12–14
bubble sort method 177–178
bubble sort method example 178–179
C
calculations, algorithm 46–48
CalcSum 185
calling a function 187
calling a function examples 187–190
calling statement 185
call function 184–185
character 2–3
character variable 6
class 222
Ed 3 BPP 4th pgs.indb 245
closing, sequential access files 205–207
compilers 4
compound If statements 71–77
compound If statement examples 71–77
constant examples 14–15
constants 8, 13
counter 115
D
data
errors 237
hierarchy 2–4
item 3
processing 23–24
processing examples 23–24
type 154
validation 77
warehouse 4
databases 3–4
date 2
date structures 2
debugging logical errors 237
design notations 224
desk checking 26, 36
display statement 185
Do loop 133–136
Do-loop-until statement 135
Do-until loop examples 142–144
Do-while loop 134
Do-while loop examples 136–142
Do-while statement 134
E
element 154
encapsulation 222–223
equals sign meanings 11
errors, data 237
evaluate algorithm 26
examples, algorithm 29
examples of names, types and values 7
2012/11/26 2:45 PM
246
•
BASIC PROGRAMMING PRINCIPLES
F
false value 6
fields 2, 3
file pointer 206
files 2, 3
fixed value 8, 14
flowcharts 29, 145–146, 230–233
For-next-loop 110–111
For-next-loop examples 111–125
for statements, nested 128–129
function
call 184–185
header 185–186
name 185–186
procedures 181, 184–192
function, no parameters 199–204
H
header, data 184–185
hierarchy chart 182
hierarchy data 2–4
I
If statement 52, 57–65, 58, 158
If statement examples 62–65
If statement testing 59–61
If statement, nested 80–86
If statement, nested in programs, examples
87–94
If statement, nested examples 82–86
If-then-else statement 52, 66
If-then-else statement examples 67–70
implementation 223
independent subprocedure examples
194–199
index 154
information 23
information hiding 222–223
inheritance 226–227
initial value 8
input 23, 205
Input/Processing/Output (IPO) chart 32–36,
37
integer variables 5–6, 15
item, data 3
interface 223
Intermediate variables 60
iteration 31, 133–136
Ed 3 BPP 4th pgs.indb 246
K
key words in arithmetic expressions 9–10
L
list all steps 25–26
logical errors, debugging 237
logical operator 54
logical operator examples 54–57
logical variable 6
loop, nested 128–129
loop, nested examples 129–132
M
main module 182
methods 221
modularisation 182
modules 181
multiple inheritance 227
N
name, function 185–186
naming a variable 4–5
naming variable rules 4
Nassi-Shneidermann diagrams (NSD) 29,
233–235
nested
for statements 128–129
If statements 80–86
If statements in programs, examples 87–94
If statement examples 82–86
loop 128–129
loop examples 129–132
non-numeric variables 6
non-zero value 6
no parameters function 199–204
no parameters subprocedure 199–204
numeric variables 5–6
O
object characteristics 220
object-oriented approach 218
object-oriented solution design 228
objects 219
one-dimensional array 154, 156–157
one-dimensional array examples 157–162,
171
OO language 219
opening sequential access files 206–207
operands 11, 13
operations, object 219, 221–222
operator precedence 55, 56
2012/11/26 2:45 PM
INDEX
operators 11–13
order of precedence 13
output 23
output files 206
relationships 224–228
return statement 185
rows 3
rules of precedence 11–13
P
paired arrays 169
parallel arrays 169
parallel arrays example 169
parameters 183–184
parentheses 12–14, 57
phases, algorithm 23
post-test loop 135
post-test loop flowcharts 146
pre-test loop 134
pre-test loop flowcharts 144–145
private attributes 223
private scope 220
problem
analysis 24–25
solving 18–19
solving steps 18–19
statement 19
statement examples 19–22
problem-solving approach 24–30
procedures, function 181, 184–192
processing 23
processing, data 23–24
processing examples, data 23–24
program planning 31–36
program planning examples 31–48
programmers 4
properties, object 219, 220–221
pseudocode 26–29, 53, 229–230
pseudocode example 26–28
public attributes 223
public scope 220
S
same sequential access files 214–217
select case structure 98–99
select case structure examples 100–103
selection 31
selection control structure 52
selection sort method 179
selection sort method example 180
sentinel 135
sequence 31
sequential access files 205–207
closing 207
opening 206–207
reading 208–211
same 214–217
writing 212–214
signature 221
solving, problem 18–19
solving steps, problem 18–19
sorting arrays 176–180
statement, problem 19
statement examples, problem 19–22
steps, algorithm 33–36, 39
string variable 6
sub class 227
sub modules 182
subprocedure call 193
subprocedure header 193–194
subprocedure, no parameters 199–204
subprocedures 181, 183, 193–204
subscript 154
super class 227
syntax errors 236–237
Q
quotes, use of 6
R
reading sequential access files 208–211
real number variables 6, 15
records 2, 3
reference parameters 183–184
referencing 155
relational comparisons 53
relational operations 53–54
relational operators 53
Ed 3 BPP 4th pgs.indb 247
•
247
T
tables 2, 3
terminating execution of a loop 135–136
testing, algorithm 36–45
text files 205
trace tables 36, 237–240
true value 6
two-dimensional arrays 171–172
type, data 154
types and values, examples of names 7
2012/11/26 2:45 PM
248
•
BASIC PROGRAMMING PRINCIPLES
U
understanding the problem 19–22
using a function 187
using a function examples 187–190
using a subprocedure 194–199
V
validation, data 77
value parameters 183
values 4
Ed 3 BPP 4th pgs.indb 248
variable examples 14–15
variable expressions 8
variable value 6–7
variables 4–8
W
walkthrough table 36
warehouse, data 4
writing, algorithm 29
writing sequential access files 212–214
2012/11/26 2:45 PM
Download
Study collections