Gr10 ITPractical Delphi
Gr10 ITPractical Delphi
INFORMATION
TECHNOLOGY
If this is your first time learning how to program, don’t worry. This textbook has been designed to teach anyone –
regardless of experience – how to program. If you follow along with all the examples then you will be an
experienced programmer who has written more than 50 programs by the end of this book.
Programming and programming languages, much like real languages, can only be learned through practice.
You cannot sit at home and learn to speak French from a textbook. In the same way, you cannot read this book
and hope to be a programmer at the end of it. Instead, you will need to write every bit of code and create every
program shown in this book. Even if all you do is follow the steps of the examples on your own computer, you
will learn how to write code. Once you have mastered the code, you will be able to comfortably use it in your
own programs.
For you to master programming, try to work through as many of the programs given to you. Each program has
been designed to both teach you new concepts and reinforce existing concepts. The book will start by teaching
you how to create simple programs. However, by the end of the book you will be creating useful programs and
fun games to play.
Programming is not only about knowing and using the programming language. There are also important
theoretical concepts that you will need to understand, and planning and problem-solving tools that you will need
to master. The best-coded program in the world will not be useful if it solves the wrong problem. This book has
therefore been divided into the following chapters:
● Chapter 1: Algorithms
● Chapter 2: Delphi WHAT MOST SCHOOLS
● Chapter 3: Variables and components DON’T TEACH
● Chapter 4: Solving basic mathematical problems using Delphi
● Chapter 5: Decision making
● Chapter 6: Validating data
● Chapter 7: Repetition
● Chapter 8: String manipulation
● Chapter 9: PAT preparation
Before getting started with algorithms, watch the video in the QR code. https://www.youtube.com/
watch?v=nKIu9yen5nc
In this unit you will look at some of the basics of creating algorithms. While there are no specific rules about
how to write an algorithm, once it is complete it should meet the following criteria:
● there must be a limited number of steps
● the steps must be:
easy to understand and follow New words
detailed and specific unambiguous – not open
To give you the most opportunities
to learn, this book will give three types ofto programming
clear and unambiguous more than one activities:
● each step should: interpretation
consist of a single task
Examples be at the most basic level that cannot be broken into simpler tasks
Examples will guide you through must
● all repetitions the creation of a program
have clear ending conditions from start to finish. All you need to do with examples
● there must be at least one result (or output).
is to follow the step-by-step guidance provided to you.
Look at the following example to help you understand the importance of following a list of instructions.
Most people have a specific way they prefer to drink their hot chocolate. The algorithm below describes one way to
make hot chocolate. While this algorithm is more difficult to create, it is a lot easier to follow and is much more likely to deliver
a tasty cake. Even if you have never baked a cake before, you should be able to use this algorithm. If you
1. Fetch a cup from the cupboard.
follow the instructions, the cake should always be a success. This algorithm can thus be called a high
2. Place the cup on the counter.
precision algorithm.
3. Add water to the kettle until there is 500 ml of water in the kettle.
4. Turn on the kettle.
ORDERto the cup.
5. Add four teaspoons of hot chocolate
6. Add 30 ml of milk to the cup.Order refers to the total number of steps needed (including repeats) to complete an algorithm. The order
of the
7. Add one teaspoon of sugar to an cup.
algorithm is usually shown as a mathematical formula based on the number of inputs. Order will have
a significant effect on the time it takes to complete an algorithm, especially when working with large
8. Stir the mixture for 10 seconds.
numbers of items.
9. Add boiling water to the cup until the cup is 95% full.
10. Stir the mixture for 10 moreFor
seconds.
example, if you have an algorithm to choose what you will wear each morning and you only have a
11. Your hot chocolate is now ready to drink!
single pair of pants, then you will only need to make one decision (wear pants or do not wear pants). If you
have a pair of pants and a shirt, then you will need to choose between four options (wear pants and a shirt,
wear only pants, wear only a shirt or wear nothing). If you have three items, you will need to choose
By following this algorithm, you should be able to make a cup of hot chocolate. However, this hot chocolate
between nine options!
might not be exactly to your taste. Think and talk to your friend about how your algorithm for making hot
chocolate (or coffee or tea) would be different to the one in the example.
Let’s work through the following activity together, and then also look at the solution.
Guided activities
Guided activities have a program
CREATING BASIC ALGORITHMS Guided Activity 1.4 Outfit selection algorithm
that you need to create on yourcan be broken into smaller steps that use algorithms designed for each of the smaller
Most algorithms
own. Your teacher steps.
will For example, in the hotDifferent
provide
people
chocolate have different
algorithm above,ways to choose
you what they
could create anwill wear in the
algorithm thatmorning. Some people will choose the first
describes
how to open the cupboard, how thingtothey see, awhile
select cup,other
howpeople can spend
to open upchocolate
the hot to an hour deciding.
container, and so forth.
you with the solution. These
This algorithm could end up being hundreds
Read through the of lines long!
following algorithms, paying careful attention to their quality.
solutions should be used as an
To prevent this, you need to focus on completing a specific task without going into detail for
opportunity to compare your
each sub-task.
Top selection
1. Open your cupboard.
program, and to see where you 2. Select the closest shirt.
But let’s begin by seeing how well you3. can followthe instructions.
may have made errors or left Select closest pair of pants.
4. Select the closest underwear.
something out. 5. Wear the selected items.
2 INFORMATION TECHNOLOGY I GRADE 10 I Practical Book
Full comparison
1. Open your cupboard.
2. Select the closest shirt.
3. Compare it with each pair of pants.
4. Give each combination a score out of 100.
Activities 5. Select the next closest shirt.
Activities are programs that your teacher can
6. give
Repeatto step
you 3as
to classroom
5 until you activities or homework.
have evaluated With these
all combinations.
7. Choose the combination with the highest score.
programs, you will only be assessed on how8.wellCompare
your program works,
the selected so usewith
combination youreach
creativity
pair oftounderwear.
come up with
a solution! 9. Give each underwear combination a score out of 100.
10. Select the combination with the highest score out of 100.
11. Wear the selected items.
Activity 1.1
Which of the following two outfit selection algorithms do you think have the highest order and precision?
1.1.1 Follow each step exactly and in the sequence indicated. Do not look at your classmates’ drawings and do not
speak to one another. Use your own interpretation of the instructions.
a. Draw a diagonal line.
b. Draw another diagonal line connected to the top of the first one.
c. Draw a straight line from the point where the diagonal lines meet.
d. Draw a horizontal line over the straight line. TERM 1 I CHAPTER 1 ALGORITHMS I UNIT 1.2 Algorithm quality 5
4.2.5 4.2.6
4 * (6/2 + 3)This is a revision activity
● FloatToStr
4 * 6
based on what/ 2/4 + 3you have covered in the chapter. Take time to answer the questions on
● FloatToInt ● Syntax errors ● Memory (where variable value is kept)
4.2.7 17 DIV 2 * (4your own.
*Naming
5 +(10 You teacher
–convention
1)) * 2.3 4.2.8may also
23
for components:MOD use3 these
*
● (13 to
DIV 2
Runtime assess
–5)
errors your
● performance
Memory address during class. Figure 9.1: Outputs for the effective use of software des
● Logic errors ● Associated with variable name
4.2.9 69 MOD (3 + ●5) +component 4.2.10
1.1 * 4.7 names (32describe
should MOD 7) * the
(26 DIV
task8) they will perform or the data
they will hold In this chapter, you will learn how to approach the
names should useactivities
CamelCase. Chapter 3: Variables And Components additional skills you could use to enhance your pro
● Consolidation
USING A TRACE TABLE ● component names should start with a three letters prefix that describes the
A trace table is a tool used 1. Inhow
to track yourthe own words, give a definition for the word ‘variable’ as it relates to computer programming.
component type. value of variables change in a program
2.
after each line of code is executed. ThisDelphi
List fi ve tool naming rulesforandtesting
is helpful conventions for variables.
an algorithm
because it helps you to determine 3. In ifyour
anownalgorithm givesis the
words, what correct result.
the difference betweenIf an
theinteger and real variable types?
result is not correct, the trace table can help you to identify the logical error
4. What is the difference between syntax, runtime and logic errors.
responsible for the incorrect result.
5. What is the purpose of a variable name?
6. Describe the relationship between the variable name and the memory location.
To create a trace table:
● identify all the variables
7. Explain the purpose of converting data types.
● create a table with a column8. for
Study theline
each following code:a separate column for
number, TERM 1 I CHAPTER 3 VARIABLES AND COMPONENTS I UNIT 3.2 Variable and component names 39
each variable, and a column forVar the output 254 INFORMATION TECHNOLOGY I GRADE 10 I Practical Book
● follow the code line-by-line and write down the new value
sName, sBirthDate : string; of the variable that
changed. iAge : Integer;
IT-Practical-LB-Gr10 INK06.indb 6 rHeight : real; 2019/09/26 09:53
TERM 1
CHAPTER
ALGORITHMS
1
CHAPTER UNITS
Unit 1.1 Basics of algorithms
Unit 1.2 Algorithm quality
Unit 1.3 Creating algorithms
Unit 1.4 Flowcharts
Learning outcomes
At the end of this chapter, you should be able to:
● explain what an algorithm is
● give examples of algorithms in everyday life
● produce an algorithm to solve a problem
● test algorithms to determine the quality and accuracy
● compare algorithms considering, for example, order and precision
● use tools, such as a basic flowchart to represent an algorithm.
INTRODUCTION
Every day of your life you make use of lists of steps to complete certain tasks.
For example, you might:
● follow a recipe ● call a friend using a phone New words
● download software or music ● read from a music sheet algorithm – an ordered list
● use a car repair manual ● follow written instructions to of steps for carrying out a
● set up a music playlist complete a task. task or solving a problem.
● follow a knitting pattern
Each list of steps for the tasks above are an example of an algorithm.
An algorithm is an ordered list of steps used to carry out a task or solve a problem.
It is important to both computers and programmers. As a programmer, your job
Take note
will be to tell a computer what to do in different situations. To do this, you can Computer programs are
create an algorithm and write a computer program. simply lists of instructions
(algorithms). If an algorithm
Before you can start creating programs and writing code, you first need to learn is not correct, it will cause
how to create an algorithm. In this chapter, you will learn more about algorithms, an error in the program you
are writing.
including what algorithms are, how to evaluate the quality of an algorithm, how to
create algorithms and how to create flowcharts.
Remember that this information will be used throughout this year when you
create programs.
In this unit you will look at some of the basics of creating algorithms. While there are no specific rules about
how to write an algorithm, once it is complete it should meet the following criteria:
● there must be a limited number of steps
● the steps must be:
easy to understand and follow New words
detailed and specific unambiguous – not open
clear and unambiguous to more than one
● each step should: interpretation
consist of a single task
be at the most basic level that cannot be broken into simpler tasks
● all repetitions must have clear ending conditions
● there must be at least one result (or output).
Look at the following example to help you understand the importance of following a list of instructions.
Most people have a specific way they prefer to drink their hot chocolate. The algorithm below describes one way to
make hot chocolate.
1. Fetch a cup from the cupboard.
2. Place the cup on the counter.
3. Add water to the kettle until there is 500 ml of water in the kettle.
4. Turn on the kettle.
5. Add four teaspoons of hot chocolate to the cup.
6. Add 30 ml of milk to the cup.
7. Add one teaspoon of sugar to the cup.
8. Stir the mixture for 10 seconds.
9. Add boiling water to the cup until the cup is 95% full.
10. Stir the mixture for 10 more seconds.
11. Your hot chocolate is now ready to drink!
By following this algorithm, you should be able to make a cup of hot chocolate. However, this hot chocolate
might not be exactly to your taste. Think and talk to your friend about how your algorithm for making hot
chocolate (or coffee or tea) would be different to the one in the example.
To prevent this, you need to focus on completing a specific task without going into detail for
each sub-task.
But let’s begin by seeing how well you can follow instructions.
1.1.1 Follow each step exactly and in the sequence indicated. Do not look at your classmates’ drawings and do not
speak to one another. Use your own interpretation of the instructions.
a. Draw a diagonal line.
b. Draw another diagonal line connected to the top of the first one.
c. Draw a straight line from the point where the diagonal lines meet.
d. Draw a horizontal line over the straight line.
e. At the bottom of the straight line, draw a curvy line.
f. Draw a diagonal line for the bottom of the first diagonal to the straight line.
g. Draw a diagonal line from the bottom of the second diagonal to the straight line.
1.1.2 Compare your picture with your partner’s.
a. Are your pictures different?
b. Can you explain why?
c. What was difficult about following the instructions?
d. What was missing from the instructions?
1.1.3 Write down the criteria that a well-designed algorithm should meet.
Your teacher will tell you what the object was that you should have drawn. Did you know
Once you know this, write a set of instructions that someone could follow
You may have discovered
to draw the object. Make sure that:
that good instructions/
● there is only one way to interpret each step, that is, the instructions
algorithms that work on a
are unambiguous first try are hard to develop.
● you provide enough detail in each step.
Activity 1.2
Write instructions (or an algorithm) that will enable someone to make a paper shape from one sheet of A4 paper.
Once your instructions (algorithm) are complete, swap them with another learner and test if it was easy to follow.
Answer the following questions.
1.2.1 Were the instructions easy to follow? Did it work?
1.2.2 If the instructions did not work, where did your classmate go wrong?
1.2.3 a. What do you need to do to fix it?
b. Adjust the instructions.
Activity 1.3
Write down instructions on how to do the following physical activities. Each activity must have at least five steps that
are properly explained.
1.3.1 How you make coffee.
1.3.2 How you do a sit-up.
1.3.3 How to buy a packet of chips at the tuckshop using a R100-note.
1.3.4 How you travel from your house to your school.
In the next unit we will explore different qualities that can help us determine whether the quality of an
algorithm is good.
This section will look at how each of these criteria are evaluated.
PRECISION
Precision refers to how accurately and reliably an algorithm solves a
problem. The more precise an algorithm is, the better it is at solving the
https://www.youtube.com/
problem correctly regardless of the situation. watch?v=c5F-mutZ7Yo
Imagine that you created the following algorithm for baking a cake.
If someone has never baked a cake before, how often do you think this algorithm will result in a
successful cake?
The problem with this algorithm is that it is not specific enough. Different people will use different amounts
of each ingredient, use different temperatures, and bake the mixture for a different length of time. Since
only a few of these attempts will result in a tasty cake, the algorithm is not very precise.
A more precise cake algorithm might look like this:
ORDER
Order refers to the total number of steps needed (including repeats) to complete an algorithm. The order
of an algorithm is usually shown as a mathematical formula based on the number of inputs. Order will have
a significant effect on the time it takes to complete an algorithm, especially when working with large
numbers of items.
For example, if you have an algorithm to choose what you will wear each morning and you only have a
single pair of pants, then you will only need to make one decision (wear pants or do not wear pants). If you
have a pair of pants and a shirt, then you will need to choose between four options (wear pants and a shirt,
wear only pants, wear only a shirt or wear nothing). If you have three items, you will need to choose
between nine options!
Let’s work through the following activity together, and then also look at the solution.
Different people have different ways to choose what they will wear in the morning. Some people will choose the first
thing they see, while other people can spend up to an hour deciding.
Read through the following algorithms, paying careful attention to their quality.
Top selection
1. Open your cupboard.
2. Select the closest shirt.
3. Select the closest pair of pants.
4. Select the closest underwear.
5. Wear the selected items.
Full comparison
1. Open your cupboard.
2. Select the closest shirt.
3. Compare it with each pair of pants.
4. Give each combination a score out of 100.
5. Select the next closest shirt.
6. Repeat step 3 to 5 until you have evaluated all combinations.
7. Choose the combination with the highest score.
8. Compare the selected combination with each pair of underwear.
9. Give each underwear combination a score out of 100.
10. Select the combination with the highest score out of 100.
11. Wear the selected items.
Which of the following two outfit selection algorithms do you think have the highest order and precision?
In terms of precision, the first algorithm will only give the best combination of clothes if the closest items
make up the best combination. The algorithm will fail most of the time and is therefore not precise. The
second algorithm will always give the best combination of clothes and is therefore more precise.
Activity 1.5
1.5.1 Write a definition for the terms order and precision and explain the difference between the two terms using
an example.
1.5.2 Different people have different ways to choose where they go shopping. Some people will choose the shop
close to where they live, while other people will drive a long distance to get to a shop where they think they
will get better discounts.
Read through the following algorithms, paying careful attention to their quality.
Shop selection
1. Estimate the distance to the shop.
2. Select the closest shop.
3. Select the groceries you want.
4. Select the teller you want to pay at.
5. Go home with your shopping.
Full comparison
1. Estimate the distance to the shop.
2. Select the shop that will offer the greatest value for money.
3. Compare it with the second choice of shop.
4. Give each shop a score out of 100.
5. Select the next closest shop.
6. Repeat step 3 to 5 until you have evaluated all combinations.
7. Choose the combination with the highest score.
8. Compare the selected combination with each distance to shop.
9. Give each shop and distance combination a score out of 100.
10. Select the combination with the highest score out of 100.
11. Visit the shop of your choice.
Which of the two shop selection algorithms do you think have the highest order and precision?
Explain your choice.
There are many possible algorithms that can be used to complete the same task and achieve the same
goal. However, not all algorithms are equally good. If someone has ever made you bad coffee or your
search engine has ever given you the wrong results, then you have seen what happens when an
algorithm fails!
So how can you make sure your algorithm does what it is supposed to do? Let’s look at some of the steps
you can follow to make sure that you are able to create high quality algorithms:
● Understanding the problem: The first step in creating an algorithm is to understand what problem
the algorithm should solve. If you don’t know this, you can easily create an awesome algorithm, but
it will solve the wrong problem.
● Defining the desired solution or output: Defining what your solution or output is, will depend on
the problem you are trying to solve. In other words, defining your desired output is closely linked to
understanding what the problem is. You may need an exact answer, or you may simply need a close
enough estimate. Defining the desired output could therefore have a significant effect on the time it
takes to solve the problem.
● Defining the inputs: The third step is to define what information you will need for the algorithm to
work. This information can be entered by a user or obtained from a different source, such as an
existing file.
● Designing a set of steps to complete the task: The fourth step is to design a set of steps that will
use your inputs to complete the task. These steps need to be specific and detailed enough that they
will always give you the correct answer.
● Testing the algorithm: Every algorithm should be tested, and not just using the situations or data
you are most likely to come across. One technique for testing an algorithm is to create a trace table.
You will learn about this in Chapter 4.
● Updating the algorithm: If your tests reveal any problems with the algorithm, you should change
the steps to fix the problem. Once changed, the new algorithm should be tested to ensure it works
as expected.
To see how these steps can be used to create an algorithm, work through the example below.
You have been asked to write an algorithm that will help your little sister to get dressed in the morning. Using the
steps listed above, create a ‘Getting dressed algorithm’.
While designing an algorithm might sound time consuming at first, it will save you a lot of time eventually.
Professional programmers spend half their time fixing problems and these problems are often caused by problems
with their algorithms. By making sure your algorithm is correct from the start, you will stop yourself from having to
first identify the mistake and then fix it later.
Watch out!
A computer program or algorithm is not like another person. It will never fill in ‘obvious’ missing information or make
assumptions. Instead, it will always do exactly what you tell it to do, even if it is obviously wrong or pointless.
Activity 1.6
Someone that has never seen your school needs to find your IT classroom when entering the school: Apply the steps
when creating the algorithm to guide the person from the gate to the IT classroom.
1.6.1 Write down what the goal of the algorithm is.
1.6.2 Write down how you will determine if the algorithm is successful.
1.6.3 Write down any information the user will need to complete your algorithm.
1.6.4 Write down the algorithm to walk from the gate to the IT classroom.
1.6.5 Swap algorithms with one of your classmates, then test each other’s algorithms.
Make sure you follow the steps exactly as they are written.
1.6.6 Update your algorithm if it did not successfully guide your classmate to the IT classroom.
1.4 Flowcharts
Input/Output Shows when data is added to the algorithm or given to the user.
Input / Output
Connector Connects one element of the algorithm to the next element. Shows
the direction in which you move from one element to the next.
By combining these items, you can visually show any algorithm. As you progress you will use different
flowchart symbols.
Here is a flowchart of an algorithm that you can use to swap the contents of container A that contains milk with
contents of container B that contains water. Study it carefully.
Begin
End
Here is a flowchart of an algorithm that you can use to determine whether a person is a male or a female using the
seventh digit of their ID number. If the seventh digit is greater than four, then the person is male, otherwise the
person is female.
Begin
Get digit
Display “Female”
End
Here is a flowchart of an algorithm that you can use to determine the area of a rectangle.
Begin
Get length
Get breadth
Determine area
Area = length × breadth
Display area
End
Begin
Get name
Get Hourly Wage
Get Hours Worked
End
● What is it?
Basics ● What is it used for?
● Order
Quality ● Precision
n
Representation ● Linguistically
● Flowchart and symbols
[Source: SA Computer Olympiad Talent Search competition, sourced from the Berbras competition]
3. The following steps, if completed correctly, will represent an algorithm to multiply a two-digit number by a
one-digit number in the form: AB × C where A, B and C represent digits, for example:
A B C
1 6 × 7
Fill in the missing instructions to complete the algorithm 4. What is the purpose of the following algorithm?
for multiplying 16 by any one-digit number (C).
Hint: C cannot be 0. Begin
Begin
True
Swap A and B A<B
End False
False
True
True
Swap A and C A<C
False
Display A
Calculate 6 × C
End
Display sum
6. The crane in the port of Lodgedam responds to six different input commands:
a. Left
b. Right
c. Up
d. Down
e. Grab
f. Release
Crate A is in the position on the left, crate B is in the position on the right. Which algorithm is the correct one to
swap the position of the two crates? Write down the letter of the correct answer.
A. (Down, Grab, Up, Right, Down, Release, Up)
B. (Down, Grab, Up, Right, Down, Release, Up) (Right, Down, Grab, Up, Left, Left. Down,
Release, Up) (Right, Down, Grab, Up, Right, Down, Release)
C. (Right, Right, Down, Grab, Up) (Left, Left, Down, Release, Up)
D. (Down, Grab, Up, Right, Right, Down, Release, Up) (Down, Grab, Left, Down, Release, Up)
(Down, Grab, Up, Right, Down, Release, Up)
[Source: SA Computer Olympiad Talent Search competition, sourced from the Berbras competition]
x x
–1
–2
–3
–4
–5
–6
y
Algorithm 1 Algorithm 2
1. Start at (5, –1) 1. Start at (5, –6)
2. From the above position, draw a diagonal line to 2. From the above position, draw a diagonal line to
(–5, –6) (–5, –1)
3. From the position in step 2, draw a straight line to 3. From the position in step 2, draw a straight line to
(5, –6) (5, –1)
4. From the position in step 3, draw a diagonal line to 4. From the position in step 3, draw a diagonal line
(–5, –1) to (–5, –6)
5. From the position in step 4, draw a diagonal line to 5. From the position in step 4, draw a straight line to
(0, 3) (5, –6)
6. From the position in step 5, draw a diagonal line to 6. From the position in step 5, draw a straight line to
(5, –1) (5, –1)
7. From the position in step 6, draw a straight line to 7. From the position in step 6, draw a diagonal line
(5, –6) to (0, 3)
8. From the position in step 2, draw a straight line to 8. From the position in step 7, draw a diagonal line
(–5, –1) to (–5, –1)
9. From the position in step 8, draw a straight line to 9. From the position in step 8, draw a straight line to
(5, –1) (–5, –6)
CHAPTER
DELPHI
2
CHAPTER UNITS
Unit 2.1: Opening Delphi and exploring the integrated development environment (IDE)
Unit 2.2: Components and properties
Unit 2.3: Creating a simple Delphi project
Unit 2.4: Events
Unit 2.5: Syntax
Learning outcomes
At the end of this chapter, you should be able to:
● clearly explain the Delphi programming environment and principles
● explain how the Delphi IDE can be used to create programs
● identify, discuss and use various Delphi components
● identify, discuss and apply different component properties
● create various Delphi events
● use the correct Delphi syntax.
INTRODUCTION
Delphi is one of many high-level programming languages. This means that it was
designed to be easier to write and be read by people. This quality makes it an Did you know
ideal language to use when learning about programming.
As you learn programming,
In this chapter, you will learn:
you should focus on
● how the Delphi IDE can be used to create programs understanding the
● how to create, open and save Delphi projects programming concepts and
● about the basic components you can use to create a simple graphical user logic. Once you understand
interface (GUI) that, learning any
● how to work with component properties programming language is
● how to create a Delphi event to change component properties and easy!
behaviour
● how to create basic Delphi code.
In this unit you will explore the Delphi IDE and begin creating simple programs.
3. The following screen will open. This is the IDE where you create applications.
TERM 1 I CHAPTER 2 DELPHI I UNIT 2.1 Opening Delphi and exploring the Delphi IDE 17
6. The Save Project As window will open again. Enter the name “HelloWorld_p” and Take note
click Save. This is the project file for the ‘Hello World’ application. ● The unit and project
7. Your application has now been saved. Every time you now make a change to the names may not contain
project, you can use the CTRL + S shortcut key to save the project. spaces.
● Add _u to the unit
Now it’s time for you to practise saving a new project. If you feel unsure of what name.
to do, refer to the example above to help you.
● Add _p to the project
name.
Activity 2.1
TERM 1 I CHAPTER 2 DELPHI I UNIT 2.1 Opening Delphi and exploring the Delphi IDE 19
COMPONENTS
In Delphi you can add images, buttons, labels and menus to a user interface in a few minutes. To create
user interfaces quickly and effectively, you need to know which components are available to you. There
are many different components that can be used in different scenarios. However, the table below lists a
few of the most important components you will use this year.
TEdit A text box that can be used to obtain text input from
users. It can also be used to display output, but this would
be by exception.
TImage A frame that can be used to display images.
PROPERTIES
Properties determine the way the components in your program look. You can change the look of your
program by changing the properties of components. Because Delphi is an object-oriented language, it
can write data to components and read data from components. For example, if you had a label component
in your program, it would have multiple properties that you could read or write to. The properties for the
label component include the caption, name, font colour, background colour and font size. You could also
change the height and width property of the label component to resize it.
The table below shows a few of the most useful properties that you can use for Delphi components:
NAME DESCRIPTION
BtnGreen
So far you have learnt about the different components in Delphi and their
properties and how to change it. When you create a program using the Delphi
IDE, you will work with two different views of the application. These are:
● design view
● code view.
You can change from design view to code view or vice versa by clicking on the
code or design tabs at the bottom of the IDE.
In this unit, you will learn more about how these views work.
4. Drag the TLabel component from the Tool Palette onto the Form.
5. You should now see the text, Label1, in the Design screen.
6. Press the CTRL + S shortcut key on your keyboard to save your project.
7. Drag the TButton component from the Tool Palette onto the form below the label.
8. Change the properties of the label and button as follows:
Example 2.3
Take note 1. Double click the [Change] button. The codeview will open and you will see the
following:
Make sure to enter the
procedure TfrmHelloDelphi.btnChangeClick(Sender:
code exactly as it is shown
TObject);
in the example. This
begin
includes the colon before
the equals sign and the
end;
semicolon at the end of the
line. 2. Add the following line of code between the begin and end lines:
lblMessage.Caption := 'Hello, Delphi!';
Take note
Take note
A statement ends with a
semicolon (;). The semicolon Label name Label property Text to change caption
tells Delphi that it is the end
lblMessage.Caption := 'Hello, Delphi!';
of a statement – in this
instance the assignment Assignment operator in Delphi
statement that will assign
text to the label caption. The assignment statement assigns the text/value on the right of the := to the left (the
Caption of the Label)
2.3.1 Add code to the [Change] button for the HelloDelphi program as follows:
procedure TFrmHelloDelphi.btnChangeClick(Sender:
TObject); Take note
begin The font style is placed
lblMessage.Caption := 'Hello, Delphi!'; between square brackets
frmHelloDelphi.Caption := 'Hello'; and starts with ‘fs’. For
lblMessage.Caption := 'Hello, World'; //add this example [fsItalic].
lblMessage.Font.Size := 48; //code
lblMessage.Font.Style := [fsItalic];
end;
2.3.2 For each of the new instructions you added, describe what happened. Hint:
Change more than one font style by separating them with commas. For example,
[fsBold, fsUnderline].
2.3.3 Open the project CodeProperties_p provided in the 02 – Code Properties folder.
The following components appear on the form in design view:
Use code so that each button will change the labels above them as shown below.
Button 4 changes the form’s caption shown below. Hint: Use the Font.Color
property to change the colour of the font.
2.3.4 After the program is run and all the buttons have been clicked, the screen above
must be displayed.
2.4 Events
Delphi is an event-driven programming language. This means that all the code inside your program must
be activated by an event (for example, when you clicked the [Change] button in the previous unit, you
triggered an OnClick_() event). In this unit you will learn more about events.
CREATING AN EVENT
An event triggers when the state of an object or component changes. This means an event occurs when
a user interacts with a component. With an OnClick_() event, the state of the object changes from ‘not
clicked’ to ‘clicked’ when you click on the BUTTON. Any code executed as a result of an event is handled
by an event handler.
For example:
Indicate an OnClick event on btnChange
Let’s create an application that shows a cute cat picture with two buttons. When the first button is clicked, the cat
picture will disappear. When the second button is clicked, the cat will appear again.
1. Create a new folder.
2. Create a new project.
3. Save the unit file in the folder you created as DisappearingCats_u.
4. Save the project in the folder you created as DisappearingCats_p.
5. Change the form’s name to “frmDisappearingCats”.
6. Change the form’s caption to “Disappearing Cats”.
7. Change the form’s height to 508 and the form’s width to 668.
8. Add a TImage component to your form from the Additional list in the Tools Palette:
In the object Inspector, look for the Picture property, then click on
the . This will open the picture editor. Click the [Load] button to
load a picture from your computer (navigate to the folder where the
picture file is stored.)
Take note
Name Caption
btnShow Show
btnHide Hide
15. Finally, select the image component and click on the three dots button next to the Picture property in the Object
Inspector
16. Click on the Load. You will need to select the picture from its file location and click on Open.
Well done! You have now created the user interface for your application.
METHODS
Components have properties and methods. You have already learnt how to change the properties of a
component. Methods are actions used to change the behaviour of a component.
For example: To hide or show this cat image imgCat we use the Hide and Show methods of imgCat:
● imgCat.hide
● imgCat.show
Now that you have created the user interface for your ‘Disappearing Cats’ application,
you can create events for the two events.
1. Open the DisappearingCat project.
2. Create an onClick event for the [Show] button. When this button is clicked, the
image must appear.
3. Create an onClick event for the [Hide] button. When this button is clicked the image
will disappear.
4. Insert the code as shown in the event handlers below
Take note
You can also press the
CTRL + SHIFT + F9
shortcut key to run your
application.
5. Save and run your application. You should now be able to hide and show the cat, by
clicking on the different buttons.
Congratulations, you have just created an application that uses two OnClick events to
show or hide an image!
Activity 2.4
2.4.1 Read the following statement, and in your own words (using an example), explain
what you understand by it.
An event triggers when the state of an object or component changes. With an
OnClick_ () event, the state of the object changes from ‘not clicked’ to ‘clicked’
when you click on the BUTTON.
2.4.2 What is an event handler?
2.4.3 Complete the sentence by filling in the missing words:
A ________ ends with a semicolon (;). The ________ tells Delphi that it is the
end of a statement.
2.4.4 Create a new project named ImageShowHide_p. Do the following:
a. Add two buttons.
b. Add two Image components: one
on top of another.
c. Load the Book Image for the first
Image component, and the
NoCamera Image for the second
Image component. The images
have been provided. Remember
to set the Stretch property so
that the pictures fit into the
Image component.
d. Create onClick_ () events for the two buttons:
i. when button 1 is clicked, the
Book image is displayed and
the NoCamera image is
hidden.
ii. when button 2 is clicked, the
NoCamera image is displayed
and the Book image is hidden
e. Save and run the project.
2.5 Syntax
Syntax refers to the specific rules of a language. For example, in English, one must follow grammatical
rules when constructing a sentence. If these rules are not followed, the sentence will not make sense nor
will it be understood.
The same is true in programming languages. Every programming language has its own sets of rules for
creating instructions for the computer. If you break even the smallest rule, you will get a syntax error and
the program will not run!
Delphi uses a compiler. A compiler checks the entire program for syntax errors before it executes.
The program will only execute when the entire program is free of syntax errors. If there are syntax errors,
the program will not execute, and the Compile dialog box will display the number of syntax errors. This is
shown in the image below:
The following lists a few of the most important Delphi syntax rules.
RULE EXAMPLE
Every statement should end with a semicolon. lblHelloWorld.Caption := 'Hello, Delphi!';
end.
Activity 2.5
2.5.1 Looking at the code from your previous three applications, write down examples
of the following syntax:
a. A statement ending in a semicolon from the DisappearingCats application.
b. A statement using the assignment operator from the HelloDelphi application.
c. Begin and end commands from the HelloDelphi application.
d. Statement referencing an object’s properties or methods using the dot
notation from the DisappearingCats application.
2.6.2 Open the project called SyntaxErrors_p from the 02 – Syntax Errors folder. The
program contains several syntax errors. Correct the syntax errors and run the
program.
Project Manager
Menu bar
Delphi IDE Object Inspector
Tool Palette
Form Designer
Components
and Placing components
Properties
Runtime view Runtime view
Events
Create Events
Note: If the visible property is set to False, the button will become invisible when the program is executed.
a. When you click on the [Stop] button, the circle shape at the top must change to red and the colour of the
other two shapes (Caution and Go!) must turn to olive and green respectively. Hint: The colour of a shape is
changed using the Brush.Color property.
b. When you click on the [Caution] button, the circle shape in the middle must change to yellow and the colour
of the other two shapes (Stop and Go!) must turn to maroon and green respectively.
c. When you click on the [Go] button, the circle shape at the bottom must change to lime and the colour of the
other two shapes (Stop and Caution) must turn to maroon and olive respectively.
Example:
btnStop is clicked btnCaution is clicked btnGo! is clicked
7. Use the knowledge and skills that you gained in this chapter and create a Delphi application to simulate a card
for a special occasion. You can choose to make a birthday card, Valentine’s day card, Mother’s day card,
invitation to a party, and so on. Refer to the SpecialOccasion_p project for some inspiration.
8. Open the project, FaultyApp_p.
The code contains syntax errors. Find the errors and correct all the errors. Once you think that you have
corrected all the errors, run to program to see if it compiles. If it does not compile, it means that you have not
corrected all the errors. Repeat the process until all errors are corrected and the program compiles correctly,
then click the buttons to see what happens.
COMPONENTS 3
CHAPTER UNITS
Unit 3.1 Data types
Unit 3.2 Variable and component names
Unit 3.3 Declaring variables and components
Unit 3.4 Assigning values to variables
Unit 3.5 Converting data types
Unit 3.6 Errors
Learning outcomes
At the end of this chapter, you should be able to:
● explore the use of variables
● use descriptive variable and component names, as well as correct naming conventions
● assign values to variables
● explore data types such as integers, strings, floats, Boolean
● identify, categorise and fix errors.
INTRODUCTION
Imagine that you had an invisible box that could store information. You could
place anything that you needed to keep or remember (like a birthdate or phone
number) inside the box. Then, when you need the information, you could simply
find the information inside the box.
Activity 3.1
In Chapter 2, you may have noticed that we spent time giving each component
a descriptive name. This helps makes the code easier to understand.
To ensure that everyone names their variables in the same way, different
Did you know
programming languages have different naming conventions. Naming The Microsoft Windows
conventions are mainly used so that programmers can understand one another’s operating system is made
code. Other than the rules below, you can name your variables whatever you up of 50 million lines of
want. Some of the naming conventions are simply a guideline to make the code. Can you imagine
program easier to understand, while others are rules that will stop your program trying to figure out how the
code works if all the
from compiling if they are not followed.
variables have names like
‘String1’ or ‘x’?
In Delphi the naming rules for variable names are:
● all variable and component names must be unique
● names may not contain spaces
● names may not start with a number, but they can contain a number
● names may not contain any special characters (like exclamation marks)
except for underscores (_). Watch out!
Variable names have no
Here are some naming conventions used for variables:
impact on the values stored
● variable names should describe the data they will contain. For example:
in variables. They simply
variable name: Amount for a variable that will hold monetary data make it easier for you to
● names should use CamelCase. This means the first word or letter is in understand what the
lowercase, and each word afterwards starts with an uppercase letter, for variable should be used for.
example, rAmountPaid
● variable names should start with a single letter prefix describing the data
type the variable will hold.
TERM 1 I CHAPTER 3 VARIABLES AND COMPONENTS I UNIT 3.2 Variable and component names 39
Activity 3.2
3.2.1 State whether the following are TRUE or FALSE. If false, motivate why it is not true.
When naming Delphi variables:
Did you know
a. Variable names may start with a number or a letter but may not contain any
You can use a label special characters.
component to place a
heading, or a description of b. Variable names should never start with a single letter that could describe the
what should be in a type of variable it is.
component or even to c. Variable names may only contain lowercase letters and you can include spaces
display output. in the name.
3.2.2 Look at the following GUI, and predict what each component will do based on the
variable name that has been assigned to it:
lblHeading
edtLength
lblArea
Input
edtWidth
btnCalcArea
btnCalcAmount
Output
lblAmount
DECLARING VARIABLES
Before you can start using a variable in Delphi, you must tell Delphi to reserve
memory space where the variable values can be kept. That is, you need to tell
New words
Delphi what the variable’s name will be and what type of data you will store in keyword – a word with a
the variable. predefined meaning in a
programming language.
The code below shows the syntax for declaring a variable. You cannot use keywords
Variables are declared in the programunder the keyword var. as variable names. It’s for
this reason that each new
variable has to be declared
var //Start of section of variables
before use.
VariableName1 : <DataType1>;
VariableName2, VariableName3, VariableName4 :
<DataType2>;
In the example above, you should take note of the following: Did you know
● The var statement is used to tell Delphi that variables will be declared.
The process of creating a
● Variables are declared by typing the variable’s name, followed by a colon (:)
variable by giving it a name
followed by the variable’s type, followed by a semicolon (;). and type is known as
● Variable definitions are indented (i.e. there is a little space before them). This declaring the variable.
makes your code easier to read.
● Multiple variables of the same type can be declared on one line, as long as
they are separated by commas.
The code below shows an example of different types of variables being declared
Take note
in Delphi. The value of variables is
only stored in your
Declaring a variable computer’s memory. When
var your program is closed, the
rTotal : Real; variable and its value
iMinimum, iMaximum : Integer; disappear from your
sName : String; computer’s memory.
cGender : Char;
bValid : Boolean;
When the program is executed, memory locations are allocated to the variables
at runtime.
iNumber := 5; Address
Name
Variable Value
TERM 1 I CHAPTER 3 VARIABLES AND COMPONENTS I UNIT 3.3 Declaring variables and Components 41
Take note Using a pen and paper, write down how you would declare the variables needed to store the
Read the section on data following information. You need to use descriptive names and decide on a suitable data type
representation in your for each variable.
Theory Book about bits 3.2.1 0.379
and bytes. 3.2.2 True
NUMBER 3.2.3 ‘f’
DATA
OF 3.2.4 1725
TYPE
BYTES 3.2.5 0.657
Integer 4 bytes 3.2.6 0152973208
Real 8 bytes 3.2.7 910229 0056 08 3
String available 3.2.8 π
memory
Character 2 bytes Once a variable has been declared, you can only store the declared or compatible
type of data in it. We can store integers in real variables BUT not real values in
Boolean 2 bytes
integer variables. An integer can be represented as a real number, but a real
number cannot be represented as an integer. Trying to store the incorrect type of
data for a variable will result in an ‘Incompatible Type’ error.
3.3.1 Identify different examples of variables from those provided above that meet the
following requirements:
a. A variable that contains a number without a decimal value.
b. A variable that contains a special character (e.g. #, %).
c. A variable that contains a number with a decimal value.
d. A variable name that contains a single character only.
e. A variable name that contains the value true or false.
f. A variable name that contains letters only.
3.3.2 Explain why:
a. sMobileNumber is declared as a string type.
b. bPensioner is declared as a Boolean type.
c. rPrice is declared as a real type.
type
TfrmReport = class (TForm)
edtName: TEdit;
edtSubject: TEdit;
edtMark1: TEdit;
edtMark2: TEdit;
lblName: TLabel;
lblSubject: TLabel;
lblMark1: TLabel;
lblMark2: TLabel;
lblOutput: TLabel;
lblReport: TLabel;
lblMarkOutput1: TLabel;
lblMarkOutput2: TLabel;
lblMarkAverage: TLabel;
btnGenerate: TButton;
pnlInput: TPanel;
pnlOutput: TPanel;
lblInput: TLabel;
Use the report card user interface and identified variables to create the four variables inside the application.
To do this:
1. Open the project stored in your 03 – Report Card folder.
2. Select the [Generate] button in the Designer screen.
TERM 1 I CHAPTER 3 VARIABLES AND COMPONENTS I UNIT 3.3 Declaring variables and Components 43
5. Add a few empty lines between the procedure’s name and the begin.
6. Add the var keyword underneath the procedure’s name in the space that you have created.
7. Declare the following two string variables: sName and sSubject.
8. Declare the following two integer variables: ‘iMark1’ and ‘iMark2.
The variable declaration should now look as follows: Take note
procedure TfrmReport.btnGenerateClick(Sender: TObject); The two strings are
var declared on the
sName, sSubject : String; same line with the
iMark1, iMark2 : Integer; variable names
begin separated by a
…. comma. The two
end; integers are also
end. declared on the
same line, separated
9. Save and run your application. If the variables were declared correctly, the by a comma.
application should open.
Well done! You have just declared your first set of variables in an application.
Activity 3.3
3.3.1 Which statement in Delphi tells it that the statements to follow are variable declarations?
3.3.2 What is the purpose of a variable declaration?
3.3.3 What is required to declare a variable?
3.3.4 Identify the errors in the following variable declarations.
Var
iNumber = Integer;
sGrade := String;
bStatus : Boolean
cDigit = char;
rNumber, iTotal : Real;
sGrade : integer;
Copy this table and complete it. Briefly describe each error and correct the error.
DECLARATION ERROR BRIEFLY DESCRIBE THE ERROR CORRECT DECLARATION STATEMENT
Once you have declared your variables, you can assign values to variable operator value
them using an assignment statement. An assignment statement
consists of a variable, an assignment operator and a value. iNumber := 12
Assignment statement
The table below shows how variables can be assigned in Delphi.
VARIABLE OPERATOR VALUE ASSIGNMENT STATEMENT
iNumber := 12; iNumber := 12;
bStatus := True; bStatus := True;
sName := ‘John’; sName := ‘John’;
NOTE:
● Values are assigned in Delphi using the colon-equals assignment operator (:=).
● The variable name appears on the left-hand side of the assignment operator.
● The values being assigned to the variables appear on the right-hand side of the assignment operator.
● To ensure the value is assigned successfully, the value on the right of the assignment operator must
be of the same type as the variable or of a compatible type.
● Once a value has been assigned to a variable, it overwrites/replaces any existing value stored in
the variable.
The code snippet below shows how you can assign values to different types of variables.
Assigning values
VAR
sName : string;
iNumber : integer;
rAverage : real;
bPass : Boolean;
begin
sName := 'Kagiso';
iNumber := 5;
rAverage := 67.74;
bPass := True;
end;
TERM 1 I CHAPTER 3 VARIABLES AND COMPONENTS I UNIT 3.4 Assigning values to variables 45
Watch out!
When a new value is assigned the previous value is overwritten/replaced.
Changing values
VAR
sName : string;
iMark : integer;
begin
sName := edit1.text
//if Kagiso is Entered in edit1
//sName will have the value Kagiso;
iMark := 75;
iMark := 77;
//The 75 in iMark will be replaced
//with 77
end;
(sMyName’s (sMyName’s
Memory
0012FC44 address is Memory Address 0012FC44 address is
Address
0012FC44) 0012FC44)
Watch out!
A variable is a symbolic name for (or reference to) a value stored in memory. Every variable has a name, a type, a
value and a location:
● Name: The name is symbolic and is how the programmer accesses the value of the variable. Every variable
must have a unique name.
● Type: The type represents what ‘kind’ of data is stored within the variable.
● Value: The value represents the contents of the variable. It can change over time. When a new value is assigned
to a variable, the existing value is replaced by the new value.
● Location: The memory cell where the value is kept.
Watch out!
A variable can only store one value at a time. If you assign a new value to it, you will
overwrite (or delete) the previous value.
Assigning a value
sName := edtName.Text;
Access the component’s property by using the component’s name, followed by a full stop, followed by the property.
This can be used to both assign a value to a property and to read a value from a property. In the code above, the
edtName component’s text value is assigned to the sName variable.
4. Using similar code, assign the text entered into the edtSubject textbox to the sSubject variable.
Assigning a value
sSubject := edtSubject.Text;
With both the learner’s name and the subject stored in a variable, you can now write these values to the output
labels. To do this:
5. Assign the value of the sName string to the lblOutput caption, as shown below:
Where the previous code snippets read the value from a component and assigned it to a variable, this code does the
reverse. It takes the value stored in the ‘sName’ variable and assigns it to the output label’s caption.
TERM 1 I CHAPTER 3 VARIABLES AND COMPONENTS I UNIT 3.4 Assigning values to variables 47
Take note
There are only a few things you can do with a variable:
Consider the statement:
iNextNumber := iNumber + 1;
● Create a variable (using the correct naming convention).
● Put some value into the variable using an assignment statement, for example, iNextNumber;
● Use the value of the variable by simply writing the name of the variable, for example, iNumber.
Activity 3.4
Open the Delphi program StringsToThings_p from the 03 – StringsToThings folder and write code for btnGetAndDisplay
that will display the information entered through each edit component on the corresponding label component.
EDIT COMPONENT
In Chapter 2 you used the Edit component to enter data. The Edit component
displays text that can be entered at runtime or design time. The Edit component,
like all the other components that you studied previously, has properties as well.
You can change the properties, such as font, text, maxlength, readOnly and
PasswordChar of an Edit component.
Label Edit
In the illustration above there are two components. These are a Label and an Edit
component. The Label prompts the user with a meaningful message of what Take note
must be entered in the Edit component. Without the Label prompt, the user will
The text property of the Edit
be left guessing what they need to enter in the Edit component.
box is used to read text
from the Edit box and is
The code to read data from an Edit component and store it in a variable is: assigned to a string
sName := edtName.text; variable, sName.
You can also convert between different data types. This conversion process is
called casting.
TERM 1 I CHAPTER 3 VARIABLES AND COMPONENTS I UNIT 3.5 Converting data types 49
To see how these commands are used in practice, work through the following guided activity.
3.4.1 For each of the functions below, write down the variable’s value and type.
a. x := FloatToStr(7321.52);
b. y := StrToFloat(‘121.3’);
c. z := StrToInt(‘15’);
d. t := IntToStr(112);
3.4.2 Indicate whether each of the following functions has the correct or incorrect input. If the input is incorrect,
provide a reason.
a. StrToInt(‘1250’);
b. StrToFloat(‘3’);
c. FloatToStr(‘10.5’);
d. IntToStr(‘321’);
Assigning a value
iMark1 := StrToInt(edtMark1.Text);
Looking at the right-side of this code, you start by reading the text stored in the edtMark1 component. Since the text
stored in these textboxes are always strings, you need to use the StrToInt function to convert the string to an integer.
Once it has been converted, you can assign the integer value to the iMark1 integer variable.
4. Assign the text entered into the edtMark2 component to the iMark2 integer variable.
iMark2 := StrToInt(edtMark2.Text);
5. Calculate the average of the two test marks. Remember your BODMAS rules.
6. To display the marks in the lblMark1 and lblMark2 labels; add the following lines of code:
lblMark1.Caption := IntToStr(iMark1);
lblMark2.Caption := IntToStr(iMark2);
In first line the integer variable iMark1 is converted to a string value and assigned to the caption of the label.
7. To display the average on the label lblAverage, convert the real average to string:
lblAverage.Caption := FloatToStr(rAverage);
TERM 1 I CHAPTER 3 VARIABLES AND COMPONENTS I UNIT 3.5 Converting data types 51
The name and surname have been stored in the wrong order. The algorithm to swap the
name and surname is as follows:
Take note ● Store the text entered in the name component in a variable, sName
When you assign ● Store the text enter in the surname component in a variable, sSurname
something to a variable, it ● Declare a third variable, sPlaceholder
will delete the content that ● Move the value of sName to sPlaceholder
is already in there, and put ● Move the value of sSurname to sName
only the new content in. ● Move the value of sPlaceholder to sSurname
You need to place what you ● Display the values of sName and sSurname on edtName and lblSurname
want to use later in another Now that you have a Name and Surname swap algorithm, you can implement it in a program.
variable, called
3.5.1 Create a project NameSwap_p.
sPlaceholder in this case,
to use it later. 3.5.2 Create the interface as shown below:
3.5.3 Create an OnClick event for the [Swap] button to swap the name and surname.
3.5.4 Save and run the project.
Activity 3.5
Create the following short Delphi programs that will help you practice what you just learned:
3.5.1 Program 1:
Create a project called School_p.
At school, you, your teachers and
your principal may all be
interested in different information.
For this program, you need to
create an application that stores
the followingsix pieces of
information usingvariables:
● The next public holiday is on 21 March.
● In the previous year, 99% of learners passed matric.
● This year’s exam dates start in November.
● In mathematics, learners struggle the most to understand the laws of
exponents.
● The tuck shop will offer a 20% discount on all cooked food next week.
● The school is currently ranked as the third best school for academics in the
province.
Once this information has been stored in variables, allow the user to click on one of
three buttons: Student, Teacher or Headmaster. Depending on the button they click,
display two pieces of information that would be useful or interesting to that person.
3.5.2 Program 2:
Open the Delphi program ShoppingListBasket_p provided in the 03 – Shopping
List folder.
SpinEdit
The program uses TSpinEdit components to component
select the quantity of the item
entered in the edit component
Take note
The value property selected
from the SpinEdit is an
integer value. If you want to
The user enters the shopping list display this value on the
item, e.g. milk, then selects the Label component, you need
quantity from the corresponding to convert it to a string type
SpinEdit component. When all the first as the caption of the
items are entered and their label is a string.
quantities are selected, the item is displayed on the corresponding label component
once the [Display] button is clicked, e.g.
Write the code for the [Display] button that will display the item and quantity on the
[Label] button when the user clicks the [Display] button.
Take note
To access the value from the SpinEdit you must use its Value property. The Value
property contains an Integer value. Look at the following code:
iItem1 := sedQuantity1.Value;
To add the item and the quantity to the [Label] button, use the following code:
The single quotes contain a space. It will ensure that a space appears between the item
name and the quantity value.
TERM 1 I CHAPTER 3 VARIABLES AND COMPONENTS I UNIT 3.5 Converting data types 53
3.6 Errors
Since different errors require different solutions, identifying the type of error you
are encountering is an important first step in solving the problem. This unit will
look at each of these errors in more detail.
SYNTAX ERRORS
Syntax refers to the form and structure of the programming language, which
defines how the symbols and keywords must be combined to format a statement.
In Delphi, the compiler checks your code against this rule. If the compiler does
not understand the statement, then a syntax error is reported.
For syntax errors, the IDE will generally warn you that you have made a mistake
and indicate the line in which the mistake occurs. Delphi will provide you with
information about the error in the Structure panel at the top left or the Messages
panel at the bottom of the Code screen. You can use the information provided to
correct the errors.
https://www.youtube.com/
watch?v=AGI371ht1N8
Runtime errors occur when you ask your program to do a task that is either
impossible or is impossible under certain circumstances. The program will then
terminate (shut down).
While creating programs this year, you may run into many different runtime errors.
One way to solve a runtime error is to step through your program by seeing how
the value in variables changes with each step of the application. In this way you
can usually identify the point at which a mistake was made. You can also search
for the error code online to see if it helps you to identify the cause of the error.
Later in the year, you will be taught how to step through a program.
The two snippets of code below are an attempt to swap a person’s name and surname.
SNIPPET ONE
SNAME := edtName.text;
SSurname := edtSurname.text;
SPlaceholder := sName;
SName := sSurname;
SSurname := sName;
SNIPPET TWO
SNAME := edtName.text;
SSurname := edtSurname.text;
SPlaceholder := sName;
SName := sSurname;
SSurname := sPlaceholder;
Work through both program snippets and answer the following questions.
3.6.1 Which one of the code snippets contains an error?
3.6.2 Explain the error
Copy and use the following table to record your findings for each program snippet:
Activity 3.6
3.6.1 Your teacher will give you three small programs. The programs can be found in the
03 – Error 1, 03 – Error 2 and 03 – Error 3 folders. For each program:
a. find and fix any coding errors that you find in the programs.
b. write down each error, provide a short explanation of the error, the type of error
and the corrected code.
1. In your own words, give a definition for the word ‘variable’ as it relates to computer programming.
2. List five Delphi naming rules and conventions for variables.
3. In your own words, what is the difference between an integer and real variable types?
4. What is the difference between syntax, runtime and logic errors.
5. What is the purpose of a variable name?
6. Describe the relationship between the variable name and the memory location.
7. Explain the purpose of converting data types.
8. Study the following code:
Var
sName, sBirthDate : string;
iAge : Integer;
rHeight : real;
cGender, cGrade : char;
bSACitizen : Boolean;
Begin
sName = 'Lerato';
cGender := 'Female';
iAge := 15
rHeight := 1.66 m;
sBirthDate := 12-09-2003;
iAge := rHeight;
bSACitizen := Yes;
cGrade := '9';
End;
Identify the errors in the code. Briefly describe each error and correct the error using the following table:
9. Study the following code and answer the questions that follow:
cInitial := edtInitial.text[1];
The [1] is the command to Delphi to use only the first character of the values in edtInitial.text. It ensures
that only ONE character is written to the variable. If there are more than 1, you will get an error message.
lblMark.Caption := strToFloat(rMarkAchieved);
cause an error?
e. What is the purpose of ‘StrToFloat’ in the following code?
rClassAvg := StrToFloat(edtClassAverage.text);
iPosition := StrToInt(spdPlace.Value);
g. Copy and complete the table to show the value that is saved in each of the variables when the program
is executed.
sSubject
cInitial
rClassAvg
iPosition
Begin
Get
name
Assign name
to variable
Get favourite
TV program
Assign TV
program to
variable
Display
variables values
End
Learning outcomes
At the end of this chapter you should be able to:
● identify, describe and apply different mathematical operators
● use the correct order of operations to solve mathematical problems
● explain and apply mathematical functions such as random, round and square root
● create Delphi programs to solve basic mathematical problems
● apply basic algorithms in programs
● use planning tools to plan solutions to problems before implementation in Delphi
● explain the difference between local and global variables and use them appropriately.
INTRODUCTION
Many mathematical problems can be solved using programming. For example, in
game pictured below, the computer will have to:
● calculate the high score obtained by a player
● determine which level a player is on
● keep the score of the current game
● keep a record of the time of the current
game.
Mathematical operators are the symbols used to tell Delphi to add, subtract, multiply or divide. In this unit you
will learn how to use basic mathematical operators to perform calculations with integers and real numbers.
Subtraction - Subtracts the second value from the first. For example:
iTotal := 5 – 3; // iTotal = 2
Real division / Divides the first value by the second. For example:
rTotal := 10 / 4; // rTotal = 2.5
Integer division div Divides the first number by the second, then discards the remainder. For example:
iResult := 10 div 3; // iResult = 3
This can only be used with integer values and the result is always an integer value.
Modulus mod Divides the first number by the second, then keeps only the remainder. For example:
iRemainder := 10 mod 3; // iRemainder = 1
This can only be used with integer values and the result is always an integer value.
Take note
Long division results in a quotient and a remainder: DIV MOD
Activity 4.1
Indicate whether the following expressions are valid or invalid. If valid, write down the answer to the calculation.
If invalid, give a reason for why you say so.
4.1.1 8 + 7 4.1.2 56.7 – 23.987
4.1.3 9 MOD 5 4.1.4 2 * 9
10
4.1.5 4.3 DIV 6 4.1.6 ___
4
4.1.7 9 DIV 2 4.1.8 7 DIV 3
4.1.9 6 MOD 9 4.1.10 6 DIV 9
4.1.11 8.5 MOD 4
Let’s look at some of the rules used for calculations when we are working in Delphi.
Example 4.1
https://www.youtube.com/
Activity 4.2 watch?v=dAgfnK528RA
Evaluate the expressions below:
4.2.1 (12 + 4 * 4) DIV 2 4.2.2 12 + 4 * 4 DIV 2
4.2.3 10 – 4 / 2* 6 + 3 4.2.4 8 * 4 – 17 / 2 + 3
4.2.5 4 * (6/2 + 3) 4.2.6 4 * 6 / 2/4 + 3
4.2.7 17 DIV 2 * (4 * 5 +(10 – 1)) * 2.3 4.2.8 23 MOD 3 * (13 DIV 2 –5)
4.2.9 69 MOD (3 + 5) + 1.1 * 4.7 4.2.10 (32 MOD 7) * (26 DIV 8)
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.1 Basic operators 63
A person buys two items and receives a 10% discount on the total price. The VAT of 15% is calculated on the
discounted total. Calculate the total before the discount was applied, the VAT amount payable, and the total due after
VAT was added on. Display the final total due.
Use the trace table below to trace through the algorithm above:
…
Var
rPrice1, rPrice2, rTotal, rVat : real;
Begin
rPrice1 := 19.40;
rPrice2 := 10.60;
rTotal := rPrice1 + rPrice2;
rTotal := rTotal * 0.90;
rVat := rTotal * 0.15;
rTotal := rTotal + rVat;
lblTotal.Caption := FloatToStr(rTotal);
End;
….
Write a program that can be used to convert temperature from degree Fahrenheit to degree Celsius.
The formula to convert degree Fahrenheit to degree Celsius is: (Fahrenheit –32)*5/9
…
Var
rDegreeFahrenheit, rDegreeCelsius : real;
Begin
rDegreeFahrenheit := StrToFloat(edtFahrenheit.Text);
rDegreeCelsius := (DegreeFahrenheit-32) * 5/9;
lblCelsius.Caption := FloatToStr(rDegreeCelsius);
End;
….
Example 4.4
Three friends Tom, Jerry and Andile need to share sweets in the ratio 3:4:5 respectively. The number of sweets is
provided by the user. Part of a sweet will not be shared. Calculate and display how many sweets each friend will
receive and how many sweets will remain after sharing takes place.
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.1 Basic operators 65
Use the trace table below to trace through the algorithm when the input for the number of sweets is 100.
Activity 4.3
Button 1 refers to problem a above, Button 2 refers to problem b above, and so on.
The formula for calculating the area of a rectangle is the length of the rectangle multiplied by the width of the rectangle.
With this in mind:
4.4.1 Create an algorithm for calculating the area of a rectangular room.
4m
3m
Activity 4.5
The code below was written to assist a school principal, who wants to build a soccer field. The principal required the
following calculations:
When the length and the width of the field is entered into the program, it should calculate the following:
● The area of the field – the formula for calculating the area is length × width
● The perimeter of the field – to calculate the perimeter you need to add each side of the field together
● The position of the half line – to determine the position of the half line, you need to find the middle of the
longest side.
Study the code below to determine if there are any errors:
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.1 Basic operators 67
A trace table will help you to identify line by line whether there are any errors. Use the table given below to trace
through the code for: iLength = 90; and iWidth = 45. When an error is found, report and correct it in the correction
table. The first error has been given to you as an example in the correction table.
TRACE TABLE
iAREA iPERIMETER
LINE
iLENGTH iWIDTH (LENGTH * (ADD ALL rHALFLINE OUTPUT
NUMBER
WIDTH) FOUR SIDES)
CORRECTION TABLE
LINE
WHAT THE CODE SHOULD DO ERROR DESCRIPTION CORRECT THE CODE
NUMBER
1 Write the value from the edit Error message. Variables iLength := StrToInt(edtLength.
box to the length variable do not have properties text)
In Delphi, you can format real numbers to display in a specific format. In this unit we will use the FloatToStrF
function to format real numbers. The FloatToStrF function converts a floating point number (real number)
into a displayable string based on a given format.
The syntax of a FloatToStrF function is: FloatToStrF(Value, Format, precision, digits) where:
● Value refers to the real number that will be converted to string
● Precision refers to the total number of digits a number will display. If the number of digits in the Value
exceeds the total number of digits in the Precision, then the Value is rounded to the total number of
digits as per the Precision
● Format indicates how a Value will be formatted into a string. The formats that we will use this
year are:
Both Precision and Format control how a Value will be formatted when displayed as a string
● Digits indicates the number of places after the decimal comma
Let’s use this information to help us fix the output for a VAT Calculator.
Example 4.5
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.2 Formatting numbers 69
9. Change the code in the procedure so that the labels make use of the FormatCurr function as shown below:
It is important to note that the FormatCurr function returns a string value. As such, you do not need to convert
the real number to a string. The FormatCurr function is an alternative to using FloatToStrF and ffCurrency.
10. Save and run the application. The output should now be much easier to read!
Congratulations! While this technique might seem like a small thing, it can make your programs a lot clearer and
easier to use. It can also be used to create a format for numbers that are not currencies.
Activity 4.6
Take note!
Surround your format string with single quotation marks. This shows that that it is a string.
4.7.1 The formula to find the gradient of a straight line given two points A(x1,y1) and B(x2,y2) is:
y2 – y1
m=
x2 – x1
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.2 Formatting numbers 71
Functions are written by the developers of Delphi. It is a segment of pre-written programming code that
performs frequently performed tasks. So far you have worked with these functions: IntToStr, FloatToStr,
StringToFloat and StringToInt (the data conversion functions); and FloatToStrF (formatting functions).
In this chapter, you will learn about the following mathematical functions:
● SQR
● SQRT
● ROUND
● TRUNC
● RANDOM
As you type the function name, Delphi provides a list that gives you the function syntax as follows:
● the function keyword
● the function name, for example, Random
● the data required by the function, for example, (const aRange: integer)
● the return type of the function, for example, :integer.
When you use any mathematical function you need to add the word Math to the Uses section of the code.
This is shown in the example below:
When a function is used, we refer to it as being called. The data provided in the function call is called
argument/s.
Take note!
If you don’t add the word Math to the Uses section of the code, the Delphi compiler will return a syntax error.
SQR FUNCTION
The square (SQR) function calculates the square of a number (that is, the number multiplied by itself, for
example, 2 multiplied by 2).
Examples
iNum:=7;
lblMessage.Caption:=IntToStr(Sqr(INum)); // the number 49 will display in the label
The statement rSquare:=Sqr(4); is equivalent to rSquare:=4 * 4;
The argument number can be either integer or real. Just like in Mathematics, you
can only find the square root of a positive number. The SQRT function always
returns a real number.
Examples
ROUND
The ROUND function is used to round a real number to the nearest integer
number.
Examples
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.3 Mathematical functions 73
The argument number is always a real number. The result is an integer. Important:
no rounding takes place.
Examples
RANDOM FUNCTION
The RANDOM function is used to generate random numbers.
Examples
rRan := random; //the result is any random real number in the range 0 to less than 1
iRandom := Random(21) //the result is an Integer number in the range 0 to 20
iRandom := Random(51)+5 //the result is an Integer number in the range 5 to 55
Randomize;
iRandom := Random(100);
Let’s work through the Guided activity below to see how these functions work in practice.
Write down code that will do the following. Assign the result to a result variable of the appropriate data type.
4.1.1 Calculate the square root of 100.
4.1.2 Select a random number between 0 and 10 (excluding 10).
4.1.3 Round the number 13.45.
4.1.4 Calculate the square of 7.1.
4.1.5 Select a random real number between 0 and 1.
4.1.6 Round the number 1578.99.
4.1.7 Round the number 42.78 down to the nearest integer.
4.1.8 Select a random number between 1 and 6 (including 6).
Activity 4.8
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.3 Mathematical functions 75
4.8.3 In a board game, two players throw a dice. The player that gets
the highest number starts the game. For example, if Player 1
throws 3 and Player 2 throws 5, Player 2 will start.
Create a Delphi project Boardgame_p that will simulate the
throw of the dice. Use the RANDOM function to determine
each player’s number.
Note: The program receives no input from the user.
Hint: A dice throw can only result in numbers 1 – 6.
4.8.4 A sphere is a perfectly round geometrical object in three-
dimensional space. The formulae to calculate the surface area
and volume of a sphere with radius, r, is:
Surface area = 4πr 2
4
Volume = __ πr 3
3
a. Open the pSphereSurfaceAreaVolume_p project from the 04 – SphereSurfaceAreaAndVolume folder provided.
b. Write code for a [Calculate] button that will read the radius of the sphere, then calculate and display the
surface area and volume.
Activity 4.9
Open the PerfectSq_p project in the 04 – Act 4.9 Error folder provided.
This program should enable the user to determine
whether a random number is a perfect square.
Take note
A perfect square is a number that
produces an integer value for its square
root. This means that the square root
does not have a decimal value.
Take note
If the square root, the trunc value and the round value are all the same; and if the square of the trunc value
is equal to the square of the round value, then the user must press the [Yes] button. Otherwise the user
must press the [No] button.
● Square the value of the square root after the decimal has been removed.
● Square the value of the square root after the square root value has been rounded off.
The program in your folder does not execute, nor does it give correct values.
a. Correct the errors in the program.
b. Test your corrected program by running it and checking whether the values are correct according to the
description of what the program should do.
c. If there are still errors, use any method that you have learnt in this chapter to find and fix the errors.
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.3 Mathematical functions 77
In this unit you will learn about another property of a variable – its scope.
If a variable needs to be accessed from more than one event handler, it must be
declared outside of the event handlers in the VAR section at the top of the
program. We say that these variables have global scope. For example, the
variable iCount in the code snippet below is declared globally. This means it can
be accessed and changed from any event handler in the program.
….
type
TForm1 = class(TForm)
btnShow : TButton;
lblMessage : TLabel;
edtName : TEdit;
lblShoutOut : TLabel;
lblOut : TLabel;
procedure btnShowClick(Sender : TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1 : TForm1;
iCount :Integer; //globsl variable
implementation
…
4.2.1 Open the Circle_p project located in the 04 – Circle folder provided.
4.2.2 The design screen will display:
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.4 Variable scope 79
4.11.1 Open the RunningTotal_p project from the 04 – Running Total folder provided. Write code for the [Find Sum]
button that will read integer values entered in the edit box and determine a running total of the numbers
entered, i.e. every time and integer value is entered, and the [Find Sum] button is clicked, the total is updated to
include the number entered and the updated total is displayed. Note, that the answer will be displayed in label
lblRunningTotal.
4.11.2 Open the MathsOperations_p project from the 04 – Mathematical Operations folder provided. The program
reads two integer numbers (once only) and determines and displays the sum, difference, product, real quotient,
integer quotient and modulus of the two numbers. Do the following:
● Local variable
Variable value only available inside the procedure where it is declared Variable
● Global variable Scope
Variable value available throughout the program
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.4 Consolidation 81
1. Explain the difference between the DIV and the MOD operators in Delphi.
2. Explain the difference between a local variable and a global variable.
3. What is the purpose of a trace table in programming?
4. Explain what an argument of a function is.
5. What is the purpose of the RANDOM function?
6. Open the RateLitresKm_p project from the
04 - RateOfLitresAndKilometres folder
provided. At the start of Thandi’s journey the
odometer reading was iStart kilometres, and at
the end of the journey her odometer reading
was iStop kilometres. Her petrol tank was full
at the start of the journey. At the end of her
journey she filled rLitres of petrol so that her
tank would be full again. Input values for iStart,
iStop and rLitres.
a. Write code for the [Calculate] button that will:
● read in the odometer reading at the start and stop of the journey
● calculate the number of litres required to fill up the tank at the end of journey.
b. Calculate and display:
● total kilometres travelled
● rate of litres per kilometre
● rate of kilometres per litre.
7. Open the ExcursionTransportation_p project located in the
04 – Excursion Transportation folder provided.
ABC school is taking learners on an excursion. They approach
a bus company for a quotation. They confirm that they have
20-seater buses and that the cost of hiring one bus is R2500.
a. Write code for the [Quotation] button to enter the total
number of learners that will be going on the excursion.
b. Determine and print the number of buses required and
the total cost of hiring the buses.
8. Open the InstallmentCalculations_p project located in
the 04 – Installment Calculation folder provided.
Nathi wants to buy a sofa from Furniture Galore Store.
He has two options to make payment for the sofa:
● Option 1: Two payments without being charged
interest, or
● Option 2: Six monthly payments. 20% interest will
be added to the cost of the sofa before the six
monthly payments are calculated.
Write code for the [Repayments] button. The button will have to read the cost of the sofa and then to
determine and print the amount for the first instalment if Option 1 is chosen, and the amount for the first
instalment if Option 2 is chosen.
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.4 Consolidation 83
12. Open the TrafficFines_p project located in the 04 – Traffic Fines folder provided.
A traffic accounts departments charges 10% interest on all
overdue fines.
a. Write code for the [Calculate] button to read in the
amount of the overdue fine, and then calculate the
interest payable and the total amount of fine payable.
The traffic accounts department only accepts amounts
converted to the nearest Rand, for example, if the amount
for an overdue fine with interest is R456.67, then the
amount payable is R457.
b. Display the amount of overdue fine, the interest on the overdue fine, total amount of fine due and total
amount payable to the traffic department.
13. Open the Parabola_p project located in the
04 – Parabola folder provided.
The equation for a parabola is: y = ax2 + bx + c
The following equations are used to find the two values for x where the graph cuts the x-axis.
_______
– b + √ b 2 – 4ac
x 1 = _____________
2a
_______
– b – √ b 2 – 4ac
x 2 = _____________
2a
a. Write code for the [Calculate] button that will allow the user to input values for a, b and c
b. Calculate and display the values for x1 and x2.
c. Test your program using the following values: a:=2, b:=3 and c:=1
14. A supplier of cooldrink cans must determine the volume of a can before it is
filled with liquid. All cans are filled with liquid.
Open the CanVolume_p project located in the 04 – Can Volume folder provide.
Write code to do the following when the [Calculate Volume] button is clicked:
a. declaring a variable for the height and radius of the can.
b. calculating the volume of the liquid required (according to the
specifications) to fill a can if the height and radius of the can
are provided as input from the user. The formula for the
volume of a cylinder is: V = πr 2h.
c. using a label to display the volume of the liquid in the can,
calculated to ONE decimal place.
Look at this example of input and output if the height of a can is
5.4 cm and the radius is 1.2 cm:
TERM 1 I CHAPTER 4 SOLVING BASIC MATHEMATICAL PROBLEMS USING DELPHI I UNIT 4.4 Consolidation 85
c. Multiplication:
Write code for the [Multiply] buttons to multiply the two numbers saved in the variables. Remember to use
the integer values for all the calculations on the left, and the real values to right. Display the answers in the
labels for output. The decimal values should display three values.
d. Division:
● Add code to the btnrDivide to divide rNum1 by a random number between 5 and 15. Display the number
in the label for real output. Round the number.
● Add code to btniMod to find the remainder of iNum1 divided by a random number between 0 and 9.
Display the answer in the label reserved for integer output.
● Add code to btniDiv to find the integer value of iNum2 divided by a random number between 1 and 10.
e. Square:
● Write code for btniSquare to display the squared value of the second number.
● Write code for the btnrSquare to display the squared value of the second number, displayed without any
decimals. DO NOT round the number.
f. Square Root
● Determine the square root of iNum1. Display the value as an integer value.
(Hint: The ROUND and TRUNC functions will remove the decimal values.)
● Determine the square root of rNum2. Display the value with one decimal value.
CHAPTER
DECISION MAKING
5
CHAPTER UNITS
Unit 5.1 Decision making algorithms
Unit 5.2 Boolean expressions and the IF-THEN statement
Unit 5.3 Boolean operators
Unit 5.4 IF-THEN-ELSE statement
Unit 5.5 Nested IF-THEN statements
Unit 5.6 CASE statements
Learning outcomes
At the end of this chapter, you should be able to:
● implement decision making in algorithms, flowcharts and code
● explain what a condition is
● use Boolean operators to create conditions
● use complex conditions in decision making.
INTRODUCTION
Every day you must make choices in your life. Think about this morning:
● When your alarm went off, did you choose to wake up or did you snooze
the alarm?
● What did you do after you got out of bed?
● Did you brush your teeth first or start by getting dressed?
● When getting dressed, did you choose to wear warm or cool clothes?
Just imagine … This is only the start of your day, and you may have had to make
so many decisions already! People make hundreds of decisions every day. These
can range from small, inconsequential decisions (such as what to wear), to large,
life changing decisions (such as deciding what to study after school).
But how does this relate to computers?
In this chapter, you will learn about the decision-making process used in Delphi.
These processes will include:
● Boolean expressions
● IF-THEN statements
● IF-THEN-ELSE statements
● Nested-IF statements
● CASE statements
You will also learn how Boolean operators can be used with these structures to
create more complex conditional statements.
When you are programming, you often need to make a decision which will help
you to solve a problem. During the decision-making process, certain conditions
(or criteria) are tested.
A condition evaluates one of the two Boolean values: TRUE or FALSE. The
outcome of the condition determines which one of the two paths (the YES/TRUE
path or the NO/FALSE path) will be followed.
Take note
You were introduced to the
In an algorithm, decision statements usually start with the word ‘if’, followed by Boolean data types in
the condition to be tested. Chapter 3.
condition ?
False/No True/Yes
False/No True/Yes
condition ?
Do you remember the algorithm for making hot chocolate from Chapter 1?
Here is what the algorithm looked like:
1. Add water to a kettle and turn the kettle on.
2. Add four teaspoons of hot chocolate to a cup.
3. Add 30 ml of milk to the cup.
4. Add one teaspoon of sugar to the cup.
5. Add boiling water from the kettle to the cup.
6. Stir the hot chocolate for 10 seconds. Your hot chocolate is now ready
to drink!
With this algorithm we found a problem: not all people make their hot chocolate
in the same way. Some people only add water, other people add milk and water.
Some people drink their hot chocolate with sugar, other people drink it without
sugar.
If the goal of the algorithm is to make tasty hot chocolate, the original algorithm
might have a lower quality since the hot chocolate would only be tasty to some
people. So, to improve the algorithm, you could build a few decisions into it.
These decisions will allow the algorithm to do one thing in some circumstances,
and something else in other circumstances.
Add teaspoon
of sugar No
Add 200 ml of
boiling water
Stir for
10 seconds
End
If you have a way (such as asking the user) of measuring whether the user wants milk or sugar, the
decision statements allow you to create a hot chocolate algorithm that is more flexible.
Let’s trace through the flowchart that was used to determine whether a number is odd or even if the input
value for the number is 5:
Activity 5.1
5.1.1 Use the skills that you have learned so far, then develop algorithms and flow charts for the following problem
situations:
a. A person must decide whether or not to take an umbrella when going to the shop.
b. Read a person’s gender in the format ‘Male’ or ‘Female’. If the person is a female display ‘F’; otherwise
display ‘M’.
5.1.2 Draw a trace table for the Even and Odd number flowchart using an input value of 6.
5.1.3 Draw a flow chart that receives a subject name and a mark out of 100 for the subject and then displays a
message ‘Pass’ if the mark is 50 or more.
BOOLEAN EXPRESSIONS
A Boolean expression is an expression that evaluates to TRUE or FALSE. There are three categories of
Boolean expressions. These are:
● Boolean variable
● Simple Boolean expressions
● Compound (complex) Boolean expressions – this will be discussed in Unit 5.3.
BOOLEAN VARIABLES
You can assign a Boolean value to a Boolean variable. For example:
● bFound := True;
● bValid := False;
The table below shows the comparison operators (relational operators) that you can use to create simple
Boolean expressions:
The computer needs to check if your name is “Sipho”. The computer needs to check if the mark is more than 30
Name = “Sipho”: Mark > 30
Var
iA, iB : Integer
sWord1 : string;
cWord2 : char;
begin
iA := 7;
iB := 7;
sWord1 := 'Seven';
cWord2 := '7';
end;
Activity 5.2
Study the following code snippet and answer the questions that follow:
Var 5.2.1 Determine whether the following statements will return TRUE or FALSE.
iA : 7; Give a reason for you answer.
iB : 7; 5.2.2 Copy and complete the table below.
sWord1 : 'Seven';
cWord2 : '7'; EXAMPLE RESULT MOTIVATION
begin iA > 2
iA := 2;
iB := 2; iA = iB
sWord1 := 'Joly'; iA >= 2
cWord2 := 'A';
iA + iB = 0
end;
iA div 2 = iA mod 2
cWord2 = 'A'
TERM 2 I CHAPTER 5 DECISION MAKING I UNIT 5.2 Boolean expressions and the If-then statement 93
In the flow chart below, block A represents statement following the THEN-keyword. Pay careful attention
to how block A is skipped if the condition is false.
Execute block A
condition ?
true
false
Block B
If <condition> then
<statement1>;
Note that the THEN-keyword it not followed by a semicolon because it is not the end of the statement.
However, the <statement1> is followed by a semicolon, and ends the IF-THEN statement.
To help you to understand how to implement the IF-THEN statement using Delphi code, work through the
following algorithm that determines if one number is a factor of another number.
A customer is awarded points on a store card. The store decides to award 1000 bonus points to all its customers.
Those customers who have points greater than 2500 before the bonus points are added, will be awarded an
additional 500 points.
Create a flowchart that you can use to read a customer’s current points on the store card, calculate the final points
after the bonus points have been allocated, then displays the customer’s final points.
Read points
points = points + 500;
points = points + 1000;
2 True
Display points Points > 2500
5
display points
End
If points equal 1200, trace through the owchart using the trace table below:
If points equal 3000, trace through the flowchart using the trace table below:
TERM 2 I CHAPTER 5 DECISION MAKING I UNIT 5.2 Boolean expressions and the If-then statement 95
2. Create an OnClick event on [Award Bonus points] button to determine the final bonus points.
Activity 5.3
Study the flowchart below and then answer the questions that follow:
Start
1
Read points
2 True
Points > 2500
5
display points
End
5.3.1 If Box 4 is moved immediately below Box 1, will the algorithm work? Explain.
5.3.2 What will happen if Box 3 and Box 4 are interchanged?
5.3.3 Use trace tables to verify your answer to questions 1 and 2 above.
5.3.4 Amend the flowchart to display the original points, as well as the final points.
Activity 5.4
Here is the syntax of an IF-THEN statement if more than one statement follows the THEN-keyword:
If <condition> then
begin
<statement1>;
<statement2>;
…
end;
Remember that the THEN and BEGIN keywords are not followed by a semicolon. However, the END
statement marking the end of the IF-THEN statement is followed by a semicolon.
Example 5.6
Activity 5.5
5.5.1 ABC stores have a promotion where a customer can win stars based on their Watch out!
spending. A customer will win one star for every R150 spent. If the customer
As a client cannot win
spends more than R4000, they receive four extra stars. Customers cannot win
part stars there must
part stars.
not be any decimal
Open the Reward_p project located in the 05 – Stars Promo folder and
numbers. Refer to
complete the program by adding code to btnCalculate to determine how many
Chapter 4 to look at the
stars a client must receive.
difference between
Test yourself: If a client enters 4150 your answer must be 31.
TRUNC and ROUND!
5.5.2 In this guessing game, a player guesses a number between 50 and 100.
The computer then displays a winning number. If the number is correct, a message with the words, ‘Great
Stuff’ is displayed to congratulate the player AND 10 marks is added to the score.
If the number is 5 less than the winning number, 1 mark is added to the player’s score and a message with
the words, ‘Keep going’ is displayed.
A player may try as many times as they please.
TERM 2 I CHAPTER 5 DECISION MAKING I UNIT 5.2 Boolean expressions and the If-then statement 97
If you want to use radio buttons in groups of two or more – as shown in the figure
alongside – the TRadioGroup component allows you to do this in a neat and
dynamic way. When radio buttons are placed on a TRadioGroup, only ONE radio
button can be selected at a time. If radio buttons are not placed in a TRadioGroup,
then the radio buttons can be selected independently.
1. Select the TRadioGroup from the Standard Palette and place it on the form. The TRadioGroup serves as a
container for the radio buttons.
2. Set the Name property of the TRadioGroup to rgpGender
3. Change the TRadioGroup caption to an appropriate name for the group of buttons, for example, ‘Gender’.
4. Select the TRadioGroup component on the form. In the Items property in the Object Inspector, click on the
ellipse (…).
5. In the StringList Editor, enter the names for the option buttons and click OK.
a. If the ItemIndex is set to -1, then none of the radio buttons will be
selected at runtime.
selected at runtime.
selected at runtime.
5.1.1 Open the Gender_p project from the 05 – Select Gender folder.
5.1.2 Create an Onclick event for the RadioButton group rgpGender so that when the
Male option is selected, the boy image is displayed. When the female option is
selected, then the girl image is displayed.
TERM 2 I CHAPTER 5 DECISION MAKING I UNIT 5.2 Boolean expressions and the If-then statement 99
5.1.3 To create the OnClick event on the rgpGender group, double click on the
rgpGender component. In the rgpGender event handler write the code (to load a
picture into the image component during run time) for each option.
imgGender.Picture.LoadFromFile('File name')
5.1.4 Save and run your project.
Take note
● Previously, you set the ItemIndex property manually
● Now we are going to check the value of the ItemIndex property. The value of the
ItemIndex property indicates which option is selected by the user.
● If the user selects the Male option, then ItemIndex will have the value 0 and if the
Female option is selected, then the ItemIndex has a value 1
● We can test which option is selected by comparing ItemIndex against 0 or 1.
Example: in the first IF-THEN statement the condition is: rgpGender.ItemIndex = 0.
This tests if the current value of ItemIndex is equal to 0.
● If the Male option is selected, then the test rgpGender.ItemIndex = 0 evaluates to
true and the Male image is loaded to the imgGender image component.
● Similarly, the female image is loaded when the Female option is selected
Activity 5.6
5.6.1 All library users pay a fee of R35.00 per month for the library services. To
encourage reading amongst learners, they are offered the following discounts.
● Pre-schoolers get a discount of 15%
● Primary school learners get a discount of 13%
● High school learners and students get a discount of 11%.
5.6.2 Open the Arithmetic_p project located in the 05 – Practise Arithmetic folder.
This program allows a user to practice their mental arithmetic. The RadioGroups
allow a user to choose the number range and operator that they would like to
practice.
Run the program and correct any errors you may encounter when the program
executes.
TERM 2 I CHAPTER 5 DECISION MAKING I UNIT 5.2 Boolean expressions and the If-then statement 101
To create compound Boolean expressions, you can use logical operators. These are:
● AND Logical Operator
● OR Logical Operator
● NOT Logical Operator
Both conditions must evaluate to TRUE for the result to be true. If either condition1 or condition2 is
FALSE, then the result will be false.
Example 5.8
If A = 5 and B = 7 then:
OR LOGICAL OPERATOR
The OR operator is used to test two conditions in the format:
(condition1) OR (condition2)
Both conditions must evaluate to FALSE for the result to be false. If either condition1 or condition2 is
TRUE, then the result will be true.
Example 5.9
If A = 5 and B = 7 then:
If the condition evaluates to TRUE, then the NOT(condition) evaluates to false. If the condition evaluates
to FALSE, then the NOT(condition) evaluates to true.
Example 5.10
If A = 5 and B = 7 then:
OPERATOR/S LEVEL
NOT 1 (highest level of precedence)
*, /, DIV, MOD, AND 2
+, -, OR 3
Activity 5.7
5.7.2 Study the code snippet below and then answer the question below. For each of the Boolean expressions (a to
e), indicate whether the expression is valid or invalid. If the expression is valid, indicate the result. If the
expression is invalid, correct the expression.
Guided Activity 5.2 Generate three random numbers and determine the largest of three numbers
5.2.1 Open the project Largest_p located in the 05 – Largest Number folder.
5.2.2 Create an OnClick event for the [Show Largest number] button.
● Generate three random numbers iNum1, iNum2 and iNum3 in the range
34 to 86.
● Display the iNum1, iNum2 and iNum3 in lblNum1, lblNum2 and lblNum3
respectively
● Determine the largest of the three numbers and display the largest
number in lblLargest.
DECISION MAKING
CHECK BOXES
Check boxes are used to give a user a YES/NO choice, for example, whether a
person is an athlete or not.
Unlike RadioButtons, you can select as many check boxes as you want. In the
example alongside, a person can select all the sporting codes that he or she
participates in.
The TGroupBox component allows you to place check boxes in a neat way. If you
need to move the check boxes to another location on the form, you simply need
to move the TGroupBox.
5.3.1 Open the SportPoint_p project located in the 05 – Sport Points folder.
NAME CAPTION
chbCricket Cricket
chbHockey Hockey
chbRugby Rugby
chbSoccer Soccer
5.3.3 Create an OnClick event for [Calculate Points] button to calculate points as follows:
● if the learner plays cricket, he or she earns 10 points
● if the learner is in Grade 10 and plays rugby or soccer, he or she earns 50 points.
5.3.4 The code for the event handler Calculate Points is:
if chbCricket.Checked then
iPoints := iPoints + 10;
● use the Checked property of the checkbox to determine whether the chbCricket is checked(selected) or
not: chbCricket.Checked
● chbCricket.Checked returns a value true if the checkbox is selected, otherwise it returns false
● the statement to award points if the learner plays cricket:
if chbCricket.Checked then // This is the same as if chbCricket.Checked = true then
iPoints := iPoints + 10;
● the statement to award points for the learner who is in Grade 10 and plays rugby or soccer is:
if (rgpGrade.ItemIndex = 0) and (chbRugby.Checked or chbSoccer.Checked) then
iPoints := iPoints + 50;
5.3.5 Save and run your program.
5.9.1 Open the SportPoint_p project used on the previous page and add code to the
Calculate Points event handler to calculate points using the following criteria:
if a learner plays any sport he or she earns 10 points.
●
5 points.
5.9.2 Save and run the project.
Example 5.12
Example 5.13
ShowMessage(‘John’+#13+’Lennon’);
This statement will result in a ShowMessage Dialog Box displaying the text ‘John
Lennon’ on two separate lines.
In the I Can Guess Game, a random number is generated. The user must guess what the
number is.
Display the following messages in ShowMessage Dialog boxes based on the user’s guess:
● ‘Number Too Low’ if the guess is less than the random generated number
● ‘Number Too High’ if the guess is greater than the random generated number
● ‘Correct’ and the random number if the guess is equal to the random generated
number
5.4.1 Open the project GuessNumber_p.dproj located in the 05 – I Can Guess folder.
5.4.2 Since the random number must be accessed from both the [Generate Random
Number] button event handler and the [Check my Number] button event handler,
the random number iNum must be declared globally:
randomize;
iNum := random(101);
● [Check my Number] button: Read the user’s guess from the edtGuess
component and store the value in iGuess. Compare the iGuess number to
the iNum value. Depending on the outcome of the comparison, show
appropriate messages in a ShowMessage Dialog box.
iGuess := StrToInt(edtGuess.text);
if iGuess > iNum then
ShowMessage('Number too high');
If iGuess < iNum then
ShowMessage('Number too low');
If iGuess = iNum then
ShowMessage('Correct'+' '+IntToStr(iNum)');
Activity 5.10
5.10.1 Open the application you wrote for the Guided activity above.
5.10.2 Add code that will allow you to keep track of the number of guesses.
If the number of guesses is more than 10 then the program must terminate.
Sometimes you may want something to happen if a condition is met, and something else to happen if the
condition is not met. Let’s look at an example:
Example 5.14
All Grade 10 learners are invited to go on an excursion. Learners who are not in Grade 10 will stay at school and
watch a movie. The condition stipulates that if a learners is in Grade 10, then the learner will go on an excursion,
else the learner will watch a movie.
false true
Grade =10 ?
Display Activity
The IF-THEN-ELSE statement executes a statement/s following the THEN-keyword when the condition is true; and
executes a statement/s following the ELSE-keyword when the condition is false.
Example 5.15
In the fl ow chart below, block A represents the statement/s following the THEN keyword. Block B represents the
statement/s following the ELSE keyword. Both paths execute Block C.
false true
Condition?
Execute Block B Execute Block A
Block B Block A
Block C
If <condition> THEN
<statement1>
ELSE
<statement2>;
If <condition> THEN
begin
<statement1>;
…
<statement4>;
end
ELSE
begin
<statement5>;
<statement6>;
…
end;
Create a program that will read the name and mark of a learner for different tests.
● If the mark is greater or equal to 50 then:
calculate a target mark for the learner’s next test by increasing the mark by 5%
set the category to ‘Olympiad candidate’
● If the mark is less than 50 then:
calculate the target mark for the learner’s next test by increasing the mark by 10%
set the category to ‘Aspiring candidate’.
5.6.2 Trace through the flowchart using the inputs John for name and 44 for the mark.
BOX NUMBER NAME MARK TARGETMARK CATEGORY MARK >= 50? OUTPUT
1 John 44
2 False
4 48 Aspiring candidate John 48 Aspiring candidate
5
Stop
5.6.3 Complete the trace table below for the flowchart using the given inputs: Mary and 57 for the mark.
BOX NUMBER NAME MARK TARGETMARK CATEGORY MARK >= 50? OUTPUT
5.6.5 Create an OnClick event for the [Status] button to determine the target mark and category and to display the
name, target mark and category of a learner. The code in the event handler for the [Status] button is:
Activity 5.11
5.11.1 Open the incomplete TestNumbers_p project located in the 05 – Test Numbers folder and complete the
program as follows:
● BtnGenerate: Complete the code for btnGenerate to
save two random numbers between 1 and 35 in
appropriate variables.
● BtnOddEven: Write code for this button to test whether
a number is an odd or even number. Display a
message with your answer.
● BtnFactor: Test if the first number is a factor of the
second number. Display a message with your answer.
● BtnSmaller: Compare the two numbers and display the smaller one.
● BtnThreeNum: Write code to place three random numbers between 1 and 20 in edtANum, edtBNum and
edtCnum respectively.
● btnArrange: Write code to place the three numbers in descending order in the three edit boxes.
5.11.2 ABC school assigns every student that enrols with a unique four digit number, for example, 1748.
This number is made up as follows:
● the first two numbers represent the year in
which the learner enrolled in any school in
Grade 8.
● the third number represents the gender of
the learner, 4 for female and 8 for males.
● The last number is a random number
between 0 and 9.
a. Create a new Delphi program with an
interface similar to the image to the right.
The user will enter his student number in the Edit box.
b. Use the StudentInformation_p project located in the 05 – Student Information folder. Write the code for
btnTest to do the following:
● use the given variables
● use div and mod functions to separate the number into the unique number, gender number and the
year enrolled
● display these values as shown in the example above
● use an IF statement to determine the gender of the student and save either ‘Male’ or ‘Female’ in a
string variable.
● the code to determine the grade is given. Read the code comments to understand what this
code does
● display all the values in a single string (as shown in the example above).
c. Test your program using the values 1748 and 1853.
5.11.3 Write an applicaton, Schoolbag_p that will calculate the approximate weight of your school bag and
categorise it according to three levels: extra load (more than 6 kg), manageable (between 3 and 6 kg,
inclusive) and lightweight (less than 3 kg). For each book in the bag:
● The user clicks on a RadioButton, in a RadioGroup, to select the book size.
● Click on [Add Book] button to record the book weight according to the size as follows:
large books weigh 900 g on average
medium books weigh 400 g on average
small books weigh 150 g on average.
● Write code for BtnGo to display the following Information:
the total number of books recorded
the weight of the bag
the category of the bag.
5.11.4 Open the Diving competition activity you completed in Activity 4.7 (use the Scoring_p project from the
04 - Scoring folder) and expand the program as follows:
a. Add two more Edit boxes with appropriate labels to record the scores of two more judges, so that five
judge’s scores are recorded.
b. Change the code for the [Final Score] button to exclude the highest and the lowest score and calculate
the average of the other three scores
Create a program that generates three random numbers between 1 and 100. Display all three numbers to the user.
If the user clicks the [Largest] button, display the value of the largest random number. If the user clicks the [Smallest]
button, display the value of the smallest number.
A nested IF-THEN statement occurs when one conditional statement is placed inside another conditional
statement. By doing this your program first checks if the outer condition has been met before looking at
the inner conditional statement.
Example 5.16
Nested-if example
if Gender = 'Male' then
begin
if Drink = 'Coke' then
ShowMessage('You get a bag')
else
ShowMessage('No bag');
end;
if Gender = 'Female' then
begin
if Drink = 'Fanta' then
ShowMessage('You get a bag')
else
ShowMessage('No bag');
end;
TERM 2 I CHAPTER 5 DECISION MAKING I UNIT 5.5 Nested if-then statements 117
Generate three random integers Num1, Num2 and Num3 in the range 0 to 100 and display the smallest of the three
numbers. You may assume that the three numbers are different.
5.7.1 The algorithm and flowchart:
5.7.2 Assume that the values 10, 25 and 12 were randomly generated for Num1, Num2 and Num3 respectively.
Trace through the flowchart using these values.
BOX NUM1 NUM2 NUM3 SMALL NUM1 < NUM2? NUM1 < NUM3? NUM2 < NUM3? OUTPUT
NUMBER
1 10 25 12
2 True
4 True
5 10
9 10
Stop
5.7.3 Trace through the flowchart using the randomly 25, 12 and 32 for Num1, Num2 and Num3 respectively.
BOX NUM1 NUM2 NUM3 SMALL NUM1 < NUM2? NUM1 < NUM3? NUM2 < NUM3? OUTPUT
NUMBER
1 25 12 32
2 False
4 True
5 12
9 12
Stop
5.7.4 Open the SmallestOfThree_p project located in the 05 – Smallest of Three folder.
a. Because Num1, Num2 and Num3 will be used by both the [Generate Numbers] button and the [Show
Smallest] buttons, they have to be declared globally.
var
Form1: TForm1;
iNum1, iNum2, iNum3: integer;
b. Create an OnClick event for the [Generate Numbers] button to generate the three random numbers
Num1, Num2 and Num3. Display the randomly generated numbers in lblNum1, lblNum2 and lblNum3.
Here is the event handler code for the [Generate Numbers] button.
TERM 2 I CHAPTER 5 DECISION MAKING I UNIT 5.5 Nested if-then statements 119
c. Create an OnClick event for the [Show Smallest] button to determine the smallest number of the three
numbers and display the smallest number in the lblSmall.
Complete the application to help a tuck shop decide how to order the drinks they sell. They want to know what the
learners prefer – cooldrink or cold water – and also whether there is a difference between what the girls and boys
prefer.
Open the Prefer_p project from the 05 – Prefer Cooldrink folder and study the interface. The application should do
the following:
TERM 2 I CHAPTER 5 DECISION MAKING I UNIT 5.5 Nested if-then statements 121
Another type of decision-making structure in Delphi is the CASE statement. Instead of using a sequence
of cascading IF-THEN-ELSE-IF statements for decision making, the CASE statement provides a tidy way
of dealing with decision-making. The cascading IF-THEN-ELSE-IF statement allows you to execute
a block code amongst different alternatives. If you are checking on a value of a single variable of the
IF-THEN-ELSE-IF statement, it is better to use the CASE statement.
A user makes a choice from a RadioButton group, and depending upon the choice he or she makes, the following is
displayed:
RADIOBUTTON MESSAGE
Coco Cola You selected Coca Cola
Creme Soda You selected Creme Soda
Fanta Grape You selected Fanta Grape
5.8.1 Open the CooldrinkSelection_p project from the 05 – Cooldrink Selector folder.
5.8.2 The code below uses nested IF-THEN-ELSE to determine the cool selected. Note that the nesting is always in
the ELSE part.
5.8.3 Now we are going to write the same code using a CASE statement. Create an OnClick event for the [Select]
button. Here is the code in the event handler:
CASE statement
procedure TForm1.btnSelectClick(Sender: TObject);
var
iSelectedIndex : integer; Did you know
begin
The CASE
iSelectedIndex := rgpCooldrinks.ItemIndex;
statement can use
case iSelectedIndex of
integers and
0 : Showmessage('You selected Coca Cola');
character variables,
1 : Showmessage('You selected Creme Soda');
but not string or
2 : Showmessage('You selected Fanta Grape');
double variables.
else
ShowMessage('You have not selected a cooldrink');
end;
end;
The CASE statement is a lot easier to read and use. It is also easier to expand or add additional values to.
As this example shows, the CASE statement can also contain an ELSE condition, which is activated when
the variable does not match any of the values.
To try out the CASE statement, work through the following example:
Learners receive a percentage mark, as well as a symbol for certain educational courses in South Africa. These
symbols might be allocated as follows:
MARK SYMBOL
80% – 100% A
70% – 79% B
0% – 69% F
The following pseudo code and flow chart were created to plan this program that converts the mark into a symbol:
BEGIN Begin
RETURN symbol
Set symbol = ‘F’ Set symbol = ‘B’ Set symbol = ‘A’
END
Return
symbol
End
Use the pseudo code and flow chart, plus the instructions below to create the program:
1. Create the following user interface.
2. Create an OnClick event for the [Convert] button.
3. Create a local integer variable called iPercentage.
4. Obtain the value of iPercentage from the text box. Remember to
convert the text in the edit box to an integer.
5. Create the following CASE statement to display the symbol.
This CASE statement reads the value of iPercentage and then compares it with the ranges from the CASE
statement. If it fi nds a match, it uses the ShowMessage dialog box to create a pop-up box with the symbol.
If no match is found, the ELSE condition activates, which creates a message with the words, Invalid mark.
6. Save and test the application.
Write a program to convert different length units according to the table shown below:
Activity 5.16
Laurens runs a gardening service, and his rates are displayed in table below:
5.16.1 Write a nested IF-statement to determine the rate per hour given the hours worked per week.
5.16.2 Determine the rate per hour using a CASE-statement.
DECISION MAKING
Decision
Making
Var
iQuarters : Integer;
sName : string;
5. Optional activity
Follow the instructions below to create a Tic Tac Toe game.
a. Create an interface as shown alongside:
Hint: Each block represents a button.
b. Create a global Boolean variable called bIsCross.
c. In the variable declaration, set the value of bIsCross to True,
as shown in the code below.
The code for the first button is shown below to help you.
Looking at the code, you will see that the first condition checks the value of bIsCross. The Boolean variable
bIsCross is used to indicate if the next move should be a cross or a naught.
If the bIsCross is True, it sets the text of btnOne to “X” (a cross) and changes the value of bIsCross to False. If it
is not True, then the ELSE statement activates which sets the caption of the button to “O” and sets the value of
bIsCross back to True.
h. Save and test your application. If you created the code correctly, your first button should swap between “X”
and “O” each time you press it.
i. In the OnClick event handler, set the caption and disable the button to prevent players from pressing it
again.
j. Copy the code to create OnClick events for all the other buttons. Make sure you change the code for each
event so that it changes the caption of the correct button!
k. Save and test your application. You should now be able to play a game of Tic Tac Toe!
CHAPTER
VALIDATING DATA
6
CHAPTER UNITS
Unit 6.1 String comparison
Unit 6.2 Validating data
Unit 6.3 IN operator
Learning outcomes
At the end of this chapter you should be able to:
● calculate the length of a string
● compare two strings based on their single character ASCII values
● check (validate) the information that users enter into a program before processing it
● use the IN operator
INTRODUCTION
In spy movies, there are often situations where one spy needs to meet another
spy and they need to make sure the person they are meeting is the correct
person. To solve this problem, the spies usually have a secret phrase that they
say at the start of the conversation, such as, “It always rains in February”. If the
first spy gives the correct greeting, and the second spy gives the correct response,
then the two spies have confirmed their identities and can have a conversation.
In computer terms, what these spies are doing is comparing responses. If the
response spoken by one spy does not match the string stored in the second
spy’s memory, then the first spy must be an imposter!
You can use a string comparison in any situation where you need to find an item,
confirm that text is correct, or create a condition based on changing values.
Figure 6.2: String comparisons can be used for usernames and passwords
In this chapter, you will learn about string comparisons. You will, more specifically,
learn how to determine if one string is larger or smaller than another string, how
to validate data and how to find a value in a list of values.
In Chapter 5 you learnt about relational operators that can be used to compare integer, real, character and
string data. In this chapter you will learn how string comparisons take place. Each character has an
American Standard Code for Information Interchange (ASCII) value. The ASCII code for a character is a
numerical value. For example, ‘A’ has the ASCII value 65, ‘B’ is 66, …, ‘Z’ is 90.
The table below shows the ASCII code for capital letter ‘A’ to ‘Z’, lower case letter ‘a’ to ‘z’ and digits 0 to 9.
You will find a full ASCII table in Annexure B at the end of this book.
Example 6.1
‘CAT’ ‘COT’
CHAR1 ASCII VALUE CHAR2 ASCII VALUE
C 67 C 67
a 97 o 111
t 116 t 116
Using the algorithm above:
● Characters in position one in both strings are equal
● Characters in position two in both strings are not equal: Char1 < Char2, therefore string1 < string2.
Hence ‘Cat’ < ‘Cot’ and the condition ‘Cat’ > ‘Cot’ is false
Considering the explanation above, arrange the following strings from the smallest to the largest.
6.1.1 ‘Benjamin’
6.1.2 ‘Ben’
6.1.3 ‘Patience’
6.1.4 ‘Peter’
6.1.5 ‘m’
6.1.6 ‘999’
6.1.7 ‘1000’
To do this, you will create a user interface for an application called Playmo.
Use the logo provided to create your smartphone login screen. To do this.
1. Open the SmartphoneLogin_p project located in the 06 – Smartphone Login folder. You should see the
following user interface.
2. Remove the caption from lblError, so that the label is empty. This label will only show a message if the user
makes a mistake.
3. Create an OnClick event for the [Log in] button.
4. Create two local string variables called sUsername and sPassword.
5. Assign any username or password to these strings in your event. Do not use your real username and password!
6. Create two new string variables called sInputUsername and sInputPassword.
7. Set the value of these two variables equal to the text from the Username and Password textboxes.
8. Create a conditional statement that checks if the username and the password is correct.
9. If both are correct, show the user a message stating that they have been logged in successfully.
10. Otherwise, update lblError so that it says, ‘Incorrect username and/or password.’ The code for this conditional
statement is shown below.
11. Save and test your application. Enter different combinations of correct and incorrect usernames to make sure
it works.
For this guided activity, you need to create an application that will use all six relational operators to compare existing
strings with strings you enter. You can start by opening the application stored in the 06 – Relational Comparisons folder.
It should have the following user interface.
The application should already have an OnClick event for the [Check] button with the following code.
OnClick event
if edtEqual.Text = lblEqualInput.Caption then
lblEqual.Caption := 'True'
else
lblEqual.Caption := 'False';
This conditional statement checks if the text entered into the first text box is equal to the text in the lblEqualInput caption
(that is, ‘Hello, World!’). If it is, it updates the lblEqual caption to say TRUE. If not, the lblEqual caption says FALSE.
Using a similar structure to this code:
6.2.1 Create similar conditional statements for the remaining relational operators.
6.2.2 Write down a value for each line that will result in the text TRUE being shown.
6.2.3 Write down a value for each line that will result in the text FALSE being shown.
6.2.4 Write down the text that is shown for each line if you leave the textboxes empty.
For question 2 and 3, you can use the application to test your own answers. The images below show two possible
answers.
Activity 6.1
Data validation is a technique used by programmers to check (or validate) the information that users
enter before processing it. This allows programmers to prevent common errors from occurring by making
sure that the information entered is correct before it is used. The goal of input validation is therefore to
prevent users from accidentally or purposefully entering incorrect data into your program.
If your program automatically generates the data it will use, you can test the data before using it. You can
also improve the algorithm generating the data to ensure that only the correct types of data are generated
for your program.
In contrast, when a user is asked to supply data for your program, many unpredictable things can happen.
The user may have:
● misunderstood what data is expected
● clicked the next button without entering data
● entered the correct data in an incorrect format
● entered the correct type of data, but an incorrect value.
This incorrect data can cause your application to crash, or even worse, provide incorrect output.
….
if edtAmount.text = '' then
ShowMessage('Enter a value') Take note
Else
rAmount := StrToFloat(edtAmount.text); ‘’ refers to a null/empty string
….
● Type validation ensures that the data entered is the correct data type. In, for example, a calculator
application, you could prevent a user from entering any values that are not numbers. Alternatively,
you could inform the user that an invalid input was entered if he or she tries to do a calculation with
letters and request them to enter the correct data type. This will be covered in Grade 11 and 12.
● Length validation ensures that the data entered is the correct length. In the Smartphone Login
application created above, you could use length validation to ensure that all passwords are at least
eight characters long. For example:
….
sPassword := edtPassword.text; Take note
if length (sPassword) >= 8 then
The Length function determines
….
the length of a string.
Else
ShowMessage('Password requires 8 or more characters');
….
iAge:=StrToInt(edtAge.text);
if (iAge>0) AND (iAge<120) then
….
Else
ShowMessage('Enter an age in the range 1 to 119');
….
To see how input validation can be used in Delphi, work through the following
guided activities.
6.4.2 For the [/ ] button (that is, the division button), add a conditional statement to make
sure the value entered into the second edit box is not 0. This prevents the program
from dividing by 0.
In both cases, you can use the ShowMessage function to inform the user if they have
entered an illegal number into the edit boxes. Once done, save the project in the
06 – Intermediate Calculator folder.
6.2.1 Your friend is a young graphic designer who has designed the following user
interface for your application, called GymRegistration_p.
a. Use this design as a basis to create a Delphi sign-up form that asks the user’s
name, surname, gender, birthdate, ID, email, cellphone number, residential
address, weight, and length.
b. Create an IPO chart for this application. In the Input section, describe five useful
input validation techniques that can be added to the form. In the Processing
section, describe how you would implement each of these input validation
techniques. Finally, in the Output section, list the error messages that you would
give to the user if the input validation is not successful.
c. Implement the input validation techniques in your application to prevent invalid
inputs.
6.2.2 Choose a program that you have created this year.
a. Describe three input validation techniques that could be added to the
application.
b. Implement one of the input validation techniques.
6.3 IN operator
In Chapter 5 you learned how to use the CASE statement to check if a variable falls within a specific range.
Specifically, you checked if a percentage value occurred in a specific range and then used the result to
display a message to the user.
IN OPERATOR
You can test if an element is included in a set of values using the IN operator. The test returns TRUE if the
element is found in the set of values; otherwise the test returns FALSE.
For example:
Var cLetter:char;
….
bFound := cLetter IN ['a','b','c'];
if bFound then
ShowMessage('Letter Valid')
else
ShowMessage('Letter Invalid');
…
Notes
● If cLetter has the value ‘a’ then bFound will be TRUE and ‘Letter Valid’ will display. Remember that
‘a’ is not the same as ‘A’
● If cLetter has any other value than ‘a’, ‘b’ or ‘c’, then bFound will be FALSE and ‘Letter Invalid’ will
display.
When creating a conditional statement, the IN operator is used in place of the equals operator because
you are using the conditional statement to see if your value can be found inside the set.
To see how a set can be used in an application, work through the following example.
You created an application that asks users to enter the day, month and year for their birthday. However, you noticed
that a small percentage of users either make typing errors or enter the correct value in the wrong place.
To fix this problem, you want to add input validation to your birthday application that will ensure the day entered is
between 1 and 31, the month is between 1 and 12, and the year is in the range 1923..2019.
To do this:
1. Create a new application and save it in the folder 06 – Birthday validation.
2. Create the following user interface.
Variable declaration
var
iDay, iMonth, iYear : Integer;
6. Read the values from the edtDay, edtMonth and edtYear component and store the values in iDay, iMonth and
iYear respectively.
Conditional statements
if not (iDay IN [1..31]) then
ShowMessage('Day is incorrect');
8. Save and test your application. Try using both valid and invalid inputs to see how the program reacts.
Congratulations! You have created an application that used sets and the IN operator to do data validation.
Activity 6.3
Using a pen and paper, write down statements that do the following.
6.3.1 Give a set that could contain any letter.
6.3.2 Give a set that could contain all the special characters that could be used as part of a password.
6.3.3 Give a set that could contain any number from 0 to 50.
6.3.4 Give a set that contains the capital letters A, B, C, D, E and F.
6.3.5 Give a set that contains the numbers 7, 12 and 25.
6.3.6 Check if the letter “c” is found in a set.
6.4.1 Complete the table below to record the possible errors and how it will be addressed. The first instance has been
done for you:
6.4.2 Use the solutions suggested in your table to write code to validate data for all input components.
VALIDATING DATA
E.g.
Test for “long” months (31 days) in a year:
The IN operator is used to see whether IF (iMonthNum IN [1,3,5,7,8,10,12]) then
one specific item forms part of a ShowMessage(‘Selected month has 31 days.’);
collection of unique ordinal items, not Test for gender in an ID-number:
The IN- IF (iRSAID[7] IN [1..4]) then
necessarily in a specific order. operator ShowMessage(‘ID comes from a female.’);
All items must be of the same data Test for a capital letter:
type to belong to one set. IF (sFirstName[1] IN [‘A’..’Z’]) then
ShowMessage(‘The first name starts with a
capital letter.’);
1. One way in which to make sure that correct data is entered by the user is through using String comparison.
a. What type of data is stored in a string variable?
b. If you want to verify a user’s password, which conditional operator would you use in your string comparison?
2. Explain how it is possible for Delphi to interpret a condition, such as, If ‘Cat’ > ’Dog’.
3. Compare the error messages below:
a. Both errors were caused by a user error. Explain the user actions that led to these errors.
b. Suggest validation techniques that you could apply to prevent this error in future.
4. Give two reasons why it is important to validate input data.
5. A user is asked to enter their cell number.
a. Name two types of validation that you would apply to ensure that the data is valid.
b. Write down pseudo code for the validation described above.
6. Describe one instance where you would use range validation.
7. Carefully consider the following statement: Valid data is not always correct.
Explain why this statement is TRUE, by giving an example.
8. Study the interface and different input components of the interface below carefully. Use the interface to create a
new program that will allow learners to enter a talent competition at your school. Add the necessary data
validation to ensure that all inputs are valid.
9. You need to generate secure IDs for your teacher to use as identification for network profiles for your
Grade 10 class.
To generate the secure ID the string is built up by:
● Adding a number that is determined by the first letter of the user’s name according to the following pattern:
A to C are represented by 1
D to F are represented by 2
G to H are represented by 3
K to L are represented by 4
M to O are represented by 5
P to S are represented by 6
S to V are represented by 7
W to Z are represented by 8
● Adding three characters entered by the user:
● Adding the age of the user
● Adding the height of the user, displaying at least one
decimal value
Open the Secure_p project from the 06 – Secure ID
folder and complete the code as follows.
a. Check that all data entered is valid.
Take note of the following:
● The first letter of the name is a capital letter.
● The user must enter any 3 characters.
● The age must be entered as an integer value and
be appropriate for Grade 10. Allow for learners
two years older and two years younger than the
usual age for Grade 10.
● The height must be entered as a real number.
b. Complete the code for btnCreate by creating a string
following the rules explained above.
c. Display the SecureID in the label, lblSecureID.
d. Save and close your program.
CHAPTER
REPETITION
7
CHAPTER UNITS
Unit 7.1 Using the ListBox and ComboBox components
Unit 7.2 Looping algorithms and flowchart
Unit 7.3 FOR loop
Unit 7.4 Using loops with components
Unit 7.5 Using the Input Box
Unit 7.6 REPEAT loop
Unit 7.7 WHILE loop
Unit 7.8 Applying loop structures
Unit 7.9 Initialising variables using the OnShow event
Unit 7.10 Timers
Learning outcomes
At the end of this chapter you should be able to:
● create and use a ListBox
● explain and apply FOR loops in your programming
● explain and apply WHILE loops in your programming
● explain and apply REPEAT loops in your programming
● initialise variables using the OnShow event
● apply loops with different components
● use the timer component to create code that runs when a timer event triggers.
INTRODUCTION
There are many situations in real life where you need to repeat the same action
until a specific goal is reached. When you practice for a sport or practice an
instrument, you repeat the same steps until you master the skill. In fact, most
people repeat the same routines: every morning they wake up and every night
they go to sleep, with only the decisions made during the day differing slightly!
Think about your morning routine. Do you need to create a new morning routine
every morning or can you simply repeat the same basic tasks each morning
without thinking?
The advantage of repeating the same tasks is that you only need to decide how
to do the task once.
So far you learned to read in data in a variable. If you need to read ten values and
keep a running total, then you could have done this in the following way:
● initialise the running total
● read a value
● update running total with this value
● read a value
● update running total with this value
● repeat until all values are read and added to the running total.
For this, you will need to write about 21 lines of code! This will make your program
long and cumbersome. Imagine how many lines of code would be required to
New words add 100 numbers!
loops – loops repeat
certain lines of code until a In Delphi, you can use looping constructs that allows you to write a set of repetitive
specific condition is met tasks once to achieve the same purpose. This chapter will teach you how to
create programming loops.
The ListBox component is used to display and manage a scrollable list of items (that is, a list of items that
you can scroll up and down in). If you can see a fully populated (top to bottom) ListBox, then a vertical
scroll bar automatically appears. The same happens with the horizontal scroll bar.
Each line inside the ListBox is called an item. In simple terms, we can think of one item as being a string
and many items as data type TStrings. TStrings represents a list of strings.
POPULATING A LISTBOX
● To populate a ListBox with items during design time from the Object Inspector:
select the ListBox
in the Items property click the ellipse (…)
a String List Editor dialog box will appear
type the list of items on separate lines in the String List Editor
click OK.
● To add an item to a ListBox during run time simply execute this code per item:
lstData.Items.Add('Butter');
TERM 3 I CHAPTER 7 REPETITION I UNIT 7.1 Using the listbox and combobox components 151
To access the content/text of the line you selected, use the following code to
retrieve the value of that specific item:
The property ItemIndex is readable and writable. This means you can assign a
value to it. If you execute the following line, you will see that line 2 will be
highlighted:
To test whether an item exists inside a ListBox you can use the method IndexOf().
IndexOf() takes one argument, the string to search for and it returns the index of
the item where the string was found.
Example 7.1
The integer iIndex will be assigned the value –1, because no Item could be found to
match ‘six’.
You can also test if an item is in the list by determining the index position of the
item. If the index position is –1, then the item is not in the list.
Example 7.2
If lstData.Items.IndexOf('Six')<>-1 then
...
Else
ShowMessage('Item not in the list');
Example 7.3
See how the tab distance grows bigger as the font size increases. However, the first
tab-stop is always positioned just after the ‘5’, that is, 20 (TabWidth) / 5 (characters) = 4
(dialog units per character).
https://www.youtube.com/
watch?v=k4RRi_ntQc8
To use the defined tab-stops (TabWidth) of a ListBox, the code must explicitly contain
the tab control character (#9), which is defined at position 9 as HT (Horizontal Tab) in the
ASCII table.
To produce the four vertical bars (as shown in the example) on the third line, you must
execute the following code:
lstData.Items.Add(#9 + '|' + #9 + '|' + #9 + '|'+ #9
+ '|');
Take note
● To activate a tabulator effect, you must set the TabWidth and include tabs (#9) in
your text.
● To adjust the correct tab width for a tabular neat output with data columns is a “trial
and error” exercise.
TERM 3 I CHAPTER 7 REPETITION I UNIT 7.1 Using the listbox and combobox components 153
Even when the ListBox is resized, it keeps the data in two columns, but rearranges
the data. The data that does not fit well is expanded to the right and can be seen
when moving the horizontal scroll bar.
Activity 7.1
You have some movies on an external hard drive. You want an application that will help you to manage your movies.
Study the interface shown on the right, then open the Movies_p project from the 07 – Movies folder file and complete the
application as follows:
7.1.1 Write code for btnLoadMovies to load the movies
from the file Movies.txt in your folder into the ListBox.
7.1.2 a. Write the code for btnFind to check whether
the movie you are looking for is in the ListBox.
The name of the movie should be entered into
edtLookFor.
b. Use a ShowMessage dialog box to indicate
whether or not the movie is found.
HINT: If the item is not in the list the index number
will be -1.
7.1.3 Add data validation to btnAdd to prevent a user from adding the text ‘Movie to Add’ to the list.
7.1.4 Write code for btnAdd to add a new movie to the list. The name of the movie should be entered in edtAdd.
7.1.5 Add code to the btnDelete event to delete a movie that a user clicked on in the ListBox.
7.1.6 Write the code for btnNumMovies to display the number of movies in the ListBox in a ShowMessage dialog box.
7.1.7 Write code for btnSaveChanges to save the content of the ListBox as it is displayed in lstMovies.
7.1.8 Save and run your app.
THE COMBOBOX
A ComboBox is a scrollable drop-down list from which a user is able to select
an item. The ComboBox is very similar to the ListBox, except that the items
are not instantly visible nor displayed. You must click on a drop-down
arrowhead to display a limited number of items. It is a component optimised
to serve as a selection tool. Both the ListBox and the ComboBox allow the
user to select only one choice at a time.
TERM 3 I CHAPTER 7 REPETITION I UNIT 7.1 Using the listbox and combobox components 155
● To add an item, for example, butter, to a ComboBox during run time, use the code found below:
● To retrieve the index of the selected item execute the code as shown below:
iIndex := cmbComboBox1.ItemIndex;
Just like the ListBox, if an item is not selected, ItemIndex returns -1 and the item position starts from 0.
● To retrieve an item from the ComboBox execute the code as shown below:
//will return an item from the list at the selected index position
sGroceryItem:=cmbComboBox1.Items[cmbComboBox1.ItemIndex];
or
or
● To count the number of items in a ComboBox execute the code as shown below:
Activity 7.2
The Subject selector application allows a user to choose subjects and display the chosen subjects in a ListBox.
Study the interface of the application shown on the right.
7.1.1 Recreate the interface of this application.
Note: the following components are used on this
interface:
● ComboBox
● ListBox
● six buttons
● four labels
7.1.2 Write the code for each button as follows:
a. [Load subject] button loads the list of subjects
from the subjectlist.txt file (provided) in the
ComboBox.
b. [Add subject to list] button adds the subject ‘Life
Orientation’ to the ComboBox.
c. The [Select] button writes the subject selected from the ComboBox to the ListBox.
d. The [Number of Subjects available] button counts the number of items in the ComboBox and displays it in
a label.
e. The [Number of Subject chosen] button counts the number of subjects in the ListBox.
f. The [Remove a subject] button deletes the Item clicked on In the ListBox.
Expand your program as follows:
● Add data validation to the [Number of subjects chosen] button to warn a user if more than seven subjects
have been selected.
● Add a button that will remove a subject from the list in the ComboBox.
TERM 3 I CHAPTER 7 REPETITION I UNIT 7.1 Using the listbox and combobox components 157
Loops are not limited for input and output purposes only. Imagine that you want to create an algorithm in
which you want to increase a counter by one until you reach 6. To do this, you could create the
following algorithm:
1. N = 0 2. N = N + 1
3. N = N + 1 4. N = N + 1
5. N = N + 1 6. N = N + 1
7. N = N + 1 8. Display N
While this algorithm would technically provide you with the correct answer, it would be a very clumsy way
of obtaining an answer. Imagine if you need to do this 1 000 times to reach a total of 1 000!
A much more efficient method of finding the answer is to create a loop in your algorithm. This loop tells
your program to repeat certain lines of code, until a condition is met.
With a loop, your program changes to:
ALGORITHM FLOWCHART
Start
Number = 0
while number < 6
1
Number = Number + 1
Number = 0
Display Number
Notes: 2 False
● number starts from an initial value of 0 Number < 6
● in this case we know that the statement True
3
Number = Number + 1 must be executed six times Number = Number + 1
● the statement Number = Number + 1 is placed inside the
loop structure
● all statement/s that appear in a loop are indented 4
Display Number
● the loop structure determines how many times it will execute
● the statement Number = Number + 1; is therefore executed
six times End
There are a number of different conditions that can be used to stop a loop:
● once it has run the required number of times
● once it reaches a certain value
● based on user input.
Example 7.4
Write an algorithm to find the sum of five integer values input by the user and display the sum of these values.
ALGORITHM FLOWCHART
Sum = 0 Begin
loop c = 1 to 5
Get X 1
Display Sum
2
Get X True
4
Sum = Sum + X END
READ NUM
The loop variable, C, is a counter that starts with an
initial value of 1. Each time the body of the loop is 5
SUM=SUM+NUM
executed, the loop counter is incremented by 1 until
C=6
6
Once the counter has reached its last value, which is 6, C=C+1
the loop is exited and the statement that follows the
loop, is executed. In this case, it is the Display Sum
statement
The flowchart representation of the algorithm is shown
on the right:
Trace through the fl owchart on the previous page using the following inputs: 8, 4, 2, 11 and 7
Using a loop in your algorithm allows it to be more flexible. For example, in the algorithm above, a statement
could be added at beginning of the algorithm to prompt the user to enter how many numbers he or she
wants to add. The integer variable, iTimes, storing this number, can then replace the end value, 5, in the
loop and the condition (test) C <= 5, will change to C <= iTimes.
The output of this activity is a Christmas tree built up of lines of x’s as shown in the figure alongside. x
xx
Follow the steps below to complete this activity: xxx
xxxx
xxxxx
7.3.1 Understand the problem: xxxxxx
xxxxxxx
xxxxxxxx
There are two loops, one to make the ‘tree’ and one to make the ‘stem’ of the tree.
●
xxxxxxxxx
xxxxxxxxxx
For the tree you need to add an x to the existing string.
●
x
x
● For the stem you need to add one x at a time. x
7.3.2 Create a flow chart for the creation of this Christmas tree.
Begin
C=1
P=1
FALSE FALSE
C <= 10 P <= 3 End
TRUE TRUE
C=C+1 P=P+1
ALGORITHM
loop C = 1 to 10
tree = tree + x
display tree
loop P = 1 to 3
stem = x
display stem
7.3.4 Draw a trace table for the algorithm above by completing the table below:
● The FOR loop needs a counter. We will call it iCount in the next example.
● The loop starts with the reserved/keyword word, FOR, and the same line ends with a DO.
● After the loop definition line, we have a BEGIN-END block of code, that will be executed several times.
● Counting from a minimum value to a maximum. Each iteration of the loop increases the counter
iCount by one. If one more than the maximum value is reached by the counter, the iteration comes to
an end and the statement after the loop is executed.
The FOR loop statement in an algorithm does not differ much from the Delphi syntax on the next page.
Let’s follow the logic flow of the FOR loop in the illustration of a more general flowchart below:
Begin
Start
iCount ← 1 I
iCount <= 10 T
False
True
Instruction to
be repeated
iCount ← iCount + 1 C
End
Let’s follow the sequence of these logic steps. Take note of the summarised I-T-C steps below:
● I for Initialize: This step initialises the counter (iCount) to the value 1.
● T for Testing: The counter is compared against the maximum or end-value (iCount <= 10) to confirm
that the loop still operates in the provided range. If the expression results to FALSE, the loop quits.
● C for Change: The third step changes the value of the counter (iCount ← iCount + 1).
Var
iCount : Integer;
begin
for iCount := 1 to 10 do
begin
// execute instruction(s)
end; // increment by 1 (always 1)
end;
● The decremental FOR loop can be identified by the command downto: For iCount := 10 downto 1
do … . It starts with a large (maximum) value to be decreased by one each time to reach the
minimum or the end-value.
Var
iCount : Integer;
begin
for iCount := 10 downto 1 do
begin
// execute instruction(s)
end; // decrement by 1 (always -1)
end;
iCount ← 10 I
T
iCount >= 1
False
True
Instruction to
be repeated
iCount ← iCount – 1 C
End
Example
var iCount:char;
begin
for iCount := 'a' to 'g' do // loop will be executed 7 times
begin
Statement/s to execute
end;
…
end;
● loop counter can only be increased or decreased by a single unit, that means that we cannot
step-up or down by 2 or 0.5
● has a START and END value. We need to know these values before the loop is activated
● counter variable’s value cannot be changed in the loop by any line of code.
Activity 7.4
● To force the program to refresh the form’s window so that you can see the updated values, insert another command:
frmFormName.Refresh; // Form’s method Refresh() is enforcing a
// visual update of the form
START VALUE END VALUE CURRENT VALUE NUMBER OF ITERATIONS QUESTION / EXPLANATION
–5 10 10 16 Why 16?
50 70
1024 2024 Adapt Sleep()-value!
10 4
–30 –10
?? ?? Add own examples
Activity 7.5
Activity 7.6
Copy the 07 – FOR Loop folder and rename the copy to 07 – FOR Loop Decrement.
7.6.1 Adapt program so that it becomes a decremental FOR loop as shown below.
7.6.2 Experiment with more input values.
Activity 7.8
Write the following FOR loops. A FOR loop that iterates from:
7.8.1 0 to 10 and shows each value.
7.8.2 1 to 100 and shows the square root of each value.
7.8.3 1 to 50 and increases the value of x by 2 inside each loop.
A factor of a number is a number that can divide into a number with no remainder, for example, 3 is a factor of 6,
because 6 ÷ 3 = 2 without a remainder. However, 3 is not a factor of 5, because 5 ÷ 3 = 1 rem 2.
Use a FOR loop to find the factors of a number.
7.9.1 Study the flow chart below and then write the algorithm for this program.
Start
Get iNum
iCount ← 1
False
iCount <= iNum Display list of factors
True End
iNum mod
iCount = 0
True
iCount = iCount + 1
7.9.2 Factorials are the product of all consecutive numbers, starting from 1, that is, 1 × 2 × 3...n where n is a
positive integer number. To determine five factorial, 5! = 5 × 4 × 3 × 2 × 1
Understand the problem:
● I need to multiply all the numbers that make up the number.
● These numbers count down from the number, for example, 5, 4, 3, 2, 1, or count up from 1 to n.
a. Why can you use a loop to shorten your code?
b. What type of loop must you use to solve this problem?
c. Write the algorithm to find the factorials of a given number.
d. Write a program to determine the factorials of a number entered by the user.
Note:
● In this code all the numbers from 1 to the value of iNumber will be checked to determine whether
they are a factor of iNumber or not.
● For example, if iNumber is 50, then each value from 1 to 50 will be checked to determine whether it
is a factor 50 or not.
Work through the following example to see how the factor finder algorithm can be improved.
To understand how the algorithm can be improved, you need to look at the factors of a few numbers:
● Factors of 10 : 1, 2, 5, 10
● Factors of 12 : 1, 2, 3, 4, 6, 12
● Factors of 27 : 1, 3, 9, 27
Can you identify a pattern from these numbers?
In each case, the product of two factors is equal to the number. Stated differently, the number divided by the one
factor will always give you another factor.
To see how this works, divide the number 10 by each of its factors:
10
___
● = 10 (this means that 1 and 10 are factors)
1
10
___
● = 5 (this means that 2 and 5 are factors)
2
10
___
● = 2 (this means that 5 and 2 are factors)
5
10
___
● = 1 (this means that 10 and 1 are factors).
10
Every factor you find is therefore directly linked to a second factor, as shown below.
Number Factors
10 1 2 5 10
This suggests that you do not need to compare all the values from 1 to the number itself to find its factors. Instead,
you (at most) need to evaluate half the numbers. In fact, if you look at the factors for the number 9, you will see that,
in order to identify all the factors, you only need to compare the numbers up to the square root of the number.
The factors for 9 are 1, 3 and 9. Dividing the number by each of the factors you see that:
● _9_ = 9 (this means that 1 and 9 are factors)
1
● _9_ = 3 (this means that 3 is a factor)
3
● _9_ = 1 (this means that 9 and 1 are factors)
9
This relationship is shown in the image below.
Number Factors
9 1 3 9
As this example shows, the biggest factor you need to evaluate is the square root of the number itself. Any number
larger than the square root can be found by dividing the number by a smaller factor. So, you can update the factor
finder program as follows:
begin
memDisplay.Lines.Clear;
iNumber := StrToInt(edtNumber.Text);
memDisplay.Lines.Add('The factors of '+IntToStr(iNumber));
iEnd := Trunc(Sqrt(iNumber));
for iCount := 1 to iEnd do
begin
if iNumber mod iCount = 0 then
begin
iFactor1 := iCount;
iFactor2 := iNumber div iCount;
if iFactor1 = iFactor2 then
memDisplay.Lines.Add(IntToStr(iCount))
else
begin
memDisplay.Lines.Add(IntToStr(iCount));
memDisplay.Lines.Add(intToStr(iFactor2));
end;
end;
end;
end;
In Chapter 4 Consolidation Activity 16 you wrote the code to determine a Fibonacci sequence by clicking on the button
each time. Open the program you wrote.
7.10.1 Open the project and study the algorithm you wrote:
a. How can you shorten or improve it?
b. Think about how you can improve the way in which this program works. Is it best to have the user click the
button repeatedly to determine the length of the sequence?
c. Rewrite the algorithm to improve it.
7.10.2 Change your program to implement your improvements.
7.10.3 Add data validation to ensure that the input from the user is valid.
Earlier in this chapter you learnt about ListBoxes, ComboBoxes and RadioButtons. Look at the examples
in the illustration below:
Add the first five integer values starting from 1 to a ListBox. Determine the sum of the values in the ListBox and display
the sum with a meaningful message in the memo box memDisplay.
7.1.1 Open the CalculateListBoxValuesSum_p project in the 07 – ListBoxSum folder. You should see the following
interface.
7.1.2 Create an OnClick event for the [Calculate Sum] button and do the following:
● Add code to store the five randomly generated integers from 0 to 99 in the lstData ListBox:
For iCount := 1 to 5 do
lstData.Items.Add(IntToStr(Random(100));
The first randomly generated number is stored in ItemIndex position 0, the second randomly generated
number is stored in ItemIndex position 1,…, the fifth randomly generated number is stored in ItemIndex
position 4
In general, the nth item in a ListBox is stored in ItemIndex position (n-1)
● Set iSum to zero
iSum=0;
● Read an item from the lstData one at a time and add it to the sum:
for iCount := 0 to lstValues.Count – 1 do
begin
iNum:=StrToInt(lstValues.Items[iCount]);
iSum:=iSum+iNum;
end;
NOTE:
● The loop counter iCount starts from 0 because the first element in the ListBox has the ItemIndex value 0.
● The maximum value is set to lstValue.count -1. lstValue.Count returns the number of items in the ListBox. So if there
are five items in the list, then lstValue.Count will return 5. Counting from 0 will give the fifth ItemIndex the value 4,
so 1 must be subtracted from lstValue.count to give the correct value for the last ItemIndex.
iNum:=StrToInt(lstValues.Items[iCount]);
● An item is retrieved from the list at the specified itemIndex and converted to integer and stored in variable iNum:
iSum:=iSum+iNum; //iSum stores a running total
● This clears the memoDisplay memo box and displays the message ‘The sum of the 5 randomly generated numbers
is: ’ and the value of the sum.
Activity 7.11
Another function you can use to get data input is the InputBox function. The InputBox function displays
an input dialog box that a user can use to enter a string, double or integer when the program is executed.
Since the InputBox is a function, it must be assigned to a variable. Let’s look at an example of this.
Example 7.6
When the above line of code is executed, the Input Dialog box will appear:
label
Default Value
The InputBox function always returns a string and hence for integer and real data the results must
be converted:
● iGrade:=StrToInt(InputBox(‘Grade’,’Enter Grade’,’10’));
● rNum:=StrToFloat(InputBox(‘Amount’,’Enter an Amount,’’));
● cResponse:=InputBox(‘Flight Seating’,’Enter your flight no’,’’)[1];
The [1] following the closing round bracket indicates to Delphi to use only the first character of the
string returned by the InputBox.
TERM 3 I CHAPTER 7 REPETITION I UNIT 7.5 Using the Input box 173
Prompt the user to enter 10 integer numbers. Determine and display the average of these numbers.
…
iSum:=0;
For iCount:=1 to 10 do
Begin
iNum:=StrToInt(InputBox('Integer Number','Enter an integer
number',''));
iSum:=iSum+iNum;
end;
rAverage:=iSum/10;
ShowMessage('The average is: '+FloatToStrF(rAverage,ffFixed,8,2));
…
Activity 7.12
7.12.1 Study the code segment and then answer the questions that follow:
Begin
…
Line 1 iNum:=StrToInt(InputBox('Chips','How many do you Require?','2'));
Line 2 cResponse:=InputBox('Response','Will you be coming?','')[1];
Line 3 memDisplay.Lines.Add('Number of Chips: '+IntToStr(iNum));
Line 4 memDisplay.Lines.Add('Attending: '+cResponse);
…
End;
c. Calculate the amount of UIF to be paid and display employee name, job description, permanent status,
amount UIF to be paid to SARS, amount UIF payable by employee and employer.
Activity 7.13
A teacher has 24 learners in her class. Create a project, Mark Statistics_p that will do the following:
7.13.1 Write code for the [TestTotal] button so that when it is clicked an InputBox appears, allowing the user to give the
maximum mark for the test.
7.13.2 Write code for the [Capture] button so that an InputBox appears when it is clicked, allowing the user to enter the
marks. This command must be placed in a loop to capture the marks of all the learners in the class. The marks
are displayed in a ListBox.
7.13.3 Add data validation to prevent the user from entering a number smaller than 0 or larger than the maximum of
the test.
7.13.4 Write code for the [Statistics] button to display the following information on the TMemo component:
a. number of learners who wrote the test
b. the average of the test, expressed as a percentage.
c. the highest mark, expressed as a percentage.
d. the lowest mark, expressed as a percentage.
e. the number of learners who achieved a mark above 80%
f. the number of learners who failed the test, given that below 40% is a fail mark.
TERM 3 I CHAPTER 7 REPETITION I UNIT 7.5 Using the Input box 175
A REPEAT…UNTIL loop has its test at the END of a loop-block. That means one iteration is always
executed before the condition is tested. The REPEAT…UNTIL loop is called a post-conditional loop
because it checks whether it should continue running at the end of each loop.
Note:
● The REPEAT…UNTIL loop structure does not need a BEGIN ... END block.
● The REPEAT marks the beginning of the loop and UNTIL marks the end of the loop.
● The statements in the loop body are executed repeatedly until the condition (a Boolean expression)
evaluates to TRUE, that is, the loop body executes when the condition is FALSE and terminates
when the condition becomes TRUE.
● The condition is tested only after the loop body has been executed.
● The loop body is executed at least once.
Begin
Start
iCount ← 0.5 I
Var Initialize Start Value
iCount : Integer;
begin
Instruction to
iCount := 0.5; be repeated
Repeat False
Change In-/Decrement
iCount ← iCount + 0.5 C
// execute instruction(s)
iCount := iCount + 0.5;
Until (iCount > 9.5); iCount > 9.5 T
end;
Test Condition True
End
The initial value is set, then the change takes place and then the test.
Example 7.8
Doubling a number
iInput := 5;
Repeat
iInput := iInput * 2;
Until iInput >= 1000;
ShowMessage(IntToStr(iInput));
Whenever you invest your money (principal) in the bank, you earn interest. This interest is added to your principal
amount and your investment grows. This is known as compounding. The compounded amount becomes the
principal amount on which the next interest will be calculated.
A client invests an amount (principal) at a fixed interest rate. The client has a target amount to reach with his or her
investment. Enter the principal amount to invest, the interest rate and the target value that the client wants to reach.
Calculate and display how many years it will take the client to reach his or her target amount. Also display the year
and the amount accumulated at the end of that year.
1. Open the CompoundInterest_p project located in the 07 – Compound Interest folder.
3. In the [Calculate] button event handler, declare the following seven local variables:
Variable Purpose
rInvestment Stores the initial investment from the edtInvestment edit box
rInterest Stores the interest percentage from the edtInterest edit box
rTarget Stores the target value from the edtTarget edit box
iYear Counter variable to store the number of years
rValue Initialised to the rInvestment amount
rGrowth Stores the interest amount calculated for a year
sValue Stores the compound value as a string for display
var
iYear : Integer;
rInvestment, rTarget,rInterest, rGrowth, rValue : Real;
sValue : String;
.
4. Assign the values entered into the Investment, Interest and Target value textboxes to the appropriate variables.
rInvestment := StrToFloat(edtInvestment.Text);
rInterest := StrToFloat(edtInterest.Text) / 100;
// interest rate divided by 100
rTarget := StrToInt(edtTarget.Text);
5. Set value of iYear to 0 and the value of rValue to the value of rInvestment. Your variable initialisation and
assignment should now look as follows:
iYear := 0;
rValue := rInvestment;
6. Clear the values of the ListBox using the Items.Clear method. Your variable initialisation and assignment should
now look as follows:
lstValues.Items.Clear;
7. Create a REPEAT…UNTIL loop that will repeat until rValue is larger than or equal to iTarget.
8. Display the number of years it will take the client to reach his or her target amount.
lblResult.Caption := IntToStr(iYear);
Let’s now apply the conditional REPEAT-UNTIL loop structure to a more mathematical challenge.
Example 7.10
The Lowest Common Multiple (LCM) or Least Common Divisor (as some call it) can demonstrate the use of a
conditional REPEAT-UNTIL loop. In mathematics the LCM is the smallest positive number that is a multiple of
both numbers. For example: Take the two numbers 6 and 15. Multiple values for each respectively would be
defined as:
6: 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, etc
15: 30, 45, 60, 75, 90, etc
Matching multiples between 6 and 15 are coloured in red and bold. The smallest or lowest matching multiple is
30. The LCM of 6 and 15 is 30.
How can we translate this into a program with Delphi code to calculate the LCM?
If we step through the multiples of one number (for example, 0, 15, 30, 45, etc) and at the same time test whether
a remainder is left if we divide with the second number, that is, if the division with the second number delivers a
remainder of 0 (zero), then we know this number is a matching multiple of both!
An algorithm in pseudo code could look as follows:
Lowest Common Multiple
BEGIN
INPUT Num1 // set Num1 15 or 6
INPUT Num2 // set Num2 6 or 15
LCMnum ← 0 // start from zero
REPEAT
LCMnum ← LCMnum + Num1 // step through: 15, 30, 45, etc.
UNTIL ((LCMnum MOD Num2) = 0) // or 6, 12, 18, 24, etc.
OUTPUT LCMnum is the calculated LCM
END
Translating this algorithm into code we would get the following possible result:
begin
1 iNum1 := StrToInt(edtNum1.Text);
2 iNum2 := StrToInt(edtNum2.Text);
3 iLCM := 0;
Repeat
4 iLCM := iLCM + iNum1
5 Until (iLCM mod iNum2) = 0;
6 lblResult.Caption := 'The LCM between ' + edtNum1.Text + ' and '
+ edtNum2.Text + ' is: ' + IntToStr(iLCM);
end;
Tracing the steps line by line in a trace table will make it even clearer.
LINE # iNUM1 iNUM2 iLCM (iLCM MOD iNUM2) =0? COMMENT
1, 2, 3 15 6 0
4 15
5 (15 MOD 6) → 3 False Keep iterating
4 30
5 (30 MOD 6) → 0 True
6 Loop terminated: LCM ← 30
Activity 7.14
Update the compound interest calculator you created in the example on page 179 so that it can do the following:
7.14.1 Ask the user to enter the number of years to invest.
7.14.2 Calculate the value of the investment after the number of years.
7.14.3 Ask the user to enter an amount to invest each year. This value must be added to the total investment at the end
of each year after the interest has already been added.
7.14.4 Display the total money invested as well as the total value of the investment at the end of the number of years.
Activity 7.15
You want to create a Delphi application to help your younger brother practise his Math. You want to start with
multiplication only. He is young, so you decide that the largest product in his times table should be 50.
Study the interface shown alongside.
Note: When the [Times Table] button is clicked an
Inputbox asks the user which table must be
displayed.
7.16.1 Write the code to display the output
as shown.
7.16.2 Use a REPEAT-UNTIL loop that will stop
when the product exceeds 50.
Extension:
7.16.3 Add one more button and an InputBox to
allow the user to input the highest value
for the product.
The WHILE loop does not necessarily run a specific number of times. Instead, the WHILE loop is a
conditional loop (like the REPEAT loop), but it places its condition first before executing the looping block.
Only if the condition is satisfied, will the loop body execute. This means that the loop body executes while
the condition is TRUE and exits the loop when the condition is FALSE.
The WHILE loop is called a pre-conditional loop because the condition that determines whether it should
run is found at the start of the loop. If the condition is TRUE, the loop activates and continues to repeat
until the condition is no longer TRUE. If the condition is not met initially, the entire loop is skipped.
iCount ← 0.5
I
Var Initialize Start Value
iCount : Integer;
begin Test Condition T
iCount := 0.5; iCount > 9.5
while (iCount <= 9.5) do
True False
begin
// execute instruction(s) Instruction to
be repeated
iCount := iCount + 0.5;
end;
end; Change In-/Decrement
iCount ← iCount + 0.5 C
End
Note:
● The loop starts with the keyword WHILE followed by the condition and then the keyword DO.
● DO is not followed by a semi-colon.
● The body of the loop appears within a BEGIN END block.
● The loop executes while the condition is TRUE and exits the loop once the condition evaluates to
FALSE.
● The loop condition is tested at the beginning of the loop. If the loop condition evaluates to FALSE
upon entering the loop then the loop is not executed at all.
The hidden loop-counter test (from the FOR loop) is replaced by a Boolean expression. Any expression
that resolves into a Boolean result is acceptable.
The loop control variable (if used as a counter) can be about any data type e.g.: Double, String. For Double
the change can include fractional parts of numbers. Integers can be increased or decreased by any
amount.
The start should be fixed before entering a WHILE loop, but the end value (part of the condition) must be
changed during the execution of the loop-block.
Example 7.11
Note:
● The While…Do loop in this example will continue multiplying iValue by 2, until the result is larger than 1000.
● When the input number is 5, the loop will run 8 times.
● If the input number is 500, the loop will only run twice.
● If the input number is 5000, the loop will not run.
Example 7.12
Determine how many multiples of a number iNum must be added together to give a sum just greater than 100.
The value of iNum must be randomly generated in the range 5 to 10. For example, if the random number 7 was
generated, then the multiples of 7 are 7, 14, 21, 28, …
Begin
…
1 iSum:=0;
2 iCount:=0;
3 Randomize;
4 iNum ;= random(6) + 5
5 iMultiple:=iNum;
6 While iSum<=100 do
7 Begin
8 iCount:=iCount+1;
9 iSum:=iSum+iMultiple;
10 iMultiple:=iMultiple+iNum;
11 End;
12 memDisplay(IntToStr(iCount),' multiples of ',IntToStr(iNum),' must be
added together');
….
End;
Note:
● Line 1: The sum variable iSum is initialised to 0. iSum :=0 refers to the I in the ITC principle
● Line 2: The counter iCount to count the number of multiples that must be added is set to 0
● Line 3: The random generator is activated
● Line 4: A random number in the range 5 to 10 is generated
● Line 5: The initial value of iNum is assigned to iMultiple
● Line 6: The condition iSum<=100 is tested. This refers to the T in the ITC principle. If the condition evaluates to
TRUE, then the body of the loop will be executed. If the condition evaluates to FALSE, then the loop is exited and
the statement in line 12 is executed
● Line7: Marks the beginning of the loop
● Line 8: The counter iCount is incremented by 1
● Line 9:The iMultiple value is added to iSum. iSum:=iSum+iMultiple; refers to the C in the ITC principle
● Line 10: The next multiple of iNum is generated in iMultiple
● Line 11: Makes the end of the loop and takes us back up to Line 6, where the condition is tested again.
Activity 7.17
Create a project called WhileLoopCounter_p in the folder 07 – While Loop Counter and create the user interface as
shown below in Design view and do the following:
7.17.1 Create an OnClick event for the [Loop] button to read the number of times the loop must execute from the Edit
component and store the value in iTimes variable.
7.17.2 Use a WHILE loop to execute the loop iTimes.
7.17.3 Display the value of the loop counter each time the loop is executed in a Message Box.
7.17.4 Save and run the project.
You need to create an application that will calculate how many times you need to roll two die before you roll a 12.
7.2.1 Open the DiceRoller_p project located in the 07 – Dice Roller folder.
7.2.2 You should see the following code in the OnClick event for the [Roll The Dice] button.
Existing code
procedure TfrmDiceRoller.btnRollTheDiceClick(Sender: TObject);
var
iCount, iDice1, iDice2, iTotal : Integer;
begin
Randomize;
lstRolls.Items.Clear;
iCount := 1;
iDice1 := Random(6) + 1;
iDice2 := Random(6) + 1;
iTotal := iDice1+iDice2; //the sum of the values on the dice are added
lstRolls.Items.Add(IntToStr(iTotal));
//Start while loop
lstRolls.Items.Add(IntToStr(iTotal));
iCount := iCount + 1;
//End while loop
In the available space, create a WHILE loop that will repeatedly roll two dice (returning a random value between
1 and 6 for each dice) until the sum of the two dice is equal to 12. With each repetition, the value of iCount
increases by 1. Once the loop stops, this value will be written to the label at the bottom of the screen.
● Before the WHILE loop, iDice1 and iDice2 are ‘rolled’ out of the loop and the total of the dices is stored in iTotal
● The loop will execute as long as iTotal is not equal to 12
● Once inside the loop, iDice1 and iDice2 are ‘rolled’ again
● The total of both dices are stored iTotal
● iCount is incremented by 1 to keep track of the number of dice rolls
● The loop will repeat as long as the iTotal is not equal to 12.
7.2.3 Save and run the project. By clicking the [Roll The Dice] button a few times, you will see that the WHILE loop
repeats a different number of times with each click. This is because random numbers are generated, it takes a
different number of rolls for the total to be equal to 12.
7.2.4 Change the code in the Onclick event handler to achieve the same results using a REPEAT…UNTIL loop.
Example 7.13
Two values are read from spin edits sedLower and sedUpper. Determine the sum of the values from sedLower to
sedUpper.
iSum:=0;
iCount:=sedLower.Value;
While iCount<=sedUpper.Value do
begin
iSum:=iSum+iCount;
iCount:=iCount+1;
end;
If a loop is counter-driven, and if we know the number of times the loop should execute, then a FOR-loop
is appropriate, however, if the loop is not controlled by a counter and you do not know beforehand how
many times the loop will repeat, you should rather use a WHILE-loop.
REPEAT-LOOP WHILE-LOOP
Prime numbers are numbers that only have two factors: 1 and the number itself. Name the project PrimeNumber_p.
Write a program that will display the first 20 prime numbers.
Hint: In activity 7.9 you wrote an algorithm to identify the factors of a number. If a number has no factors other than
itself and 1, it is a prime number.
Activity 7.19
Continue working in the program you created in Activity 7.16 on page 181.
Your brother needs to practise his multiplication. Change your program as follows:
7.19.1 Add the [Multiplication] button.
7.19.2 Write code for this button to:
a. randomly select two numbers between 0 to 10 to multiply.
b. generate the correct answer to this sum by multiplying the two random numbers.
c. display the question in labels as shown In the Image on the below.
An imaginary Pharaoh wants to build a solid pyramid. He needs to order the blocks to build the pyramid from a stone
cutter who will transport the blocks.
Write an app that will calculate and display the number of blocks the Pharaoh needs to order.
Understand the problem:
● A pyramid is built up from a
square base.
● This is a solid pyramid; therefore
the area of the square has to be
filled with blocks.
● Each level has fewer blocks than
the previous level.
● The top level consists of a
limited number of blocks.
● Which values do you need to get
from the user?
In Chapter 4 you had to correct the output of a program to order healthy meals from the tuck shop.
Open the PreOrder_p project used in Activity 4.7.3 and improve the program so that it only calculates the order once
the user indicates that the order is complete.
Improve the program by following the guidelines below:
7.21.1 Change the interface so that it looks similar
to the one shown alongside.
Note: The menu is placed in a groupbox.
The spin edits are removed and replaced by
a button.
7.21.2 Add code to btnOrder to use an InputBox for
the user to enter his order. Once an item has
been ordered, increase the number of items
ordered and add to the total amount owed. A
message should appear to ask if the order is
complete. If the answer is ‘No’, another
InputBox should appear, but if the answer is
‘Yes’ btnCalculate should be enabled, and
the loop stops.
Hint: Create a Boolean variable bStop and set the value to false.
The while do loop is then:
7.21.3 Change the code to btnCalculate to use the values saved in the global variables to calculate the total amount of
items ordered as well as the total amount owed. Display these values in the labels on the form.
7.21.4 Run your program.
In this unit we will look at another example that is a bit more complicated.
Example 7.13
The Greatest Common Divisor (GCD) is a mathematical challenge and well solved by applying the Euclidean
Algorithm. It refers to the largest natural number that divides into two or more non-zero integers without a
remainder. We will only apply it to two numbers. For example:
● the GCD of 8 and 12 is 4. The number 2 would also be a divisor, but it is not the greatest common divisor.
● the GCD of 9 and 18 is 9.
● the GCD of 24 and 18 is 6.
A good reverse check would be to write down multiples of your answer. The sequence of numbers being created
should contain the two original numbers for the GCD-testing. Take the last example with a result of 6. The multiples
of 6 are: 6, 12, 18, 24, 30, 36, and so on. Here you see the original GCD-testing numbers printed in bold.
So, how can we develop an algorithm and/or a small project to calculate the GCD of two numbers?
Let’s begin by demonstrating one interpretation we can use for our algorithm to be developed.
Assume we have the two numbers 135 and 36. Applying the Euclidian Algorithm we would do the following:
The iteration is based on the condition that the remainder of the two numbers Num1 and Num2 is larger than zero
(that is not equal to zero). As part of each iteration:
● the remainder (Remain) is calculated from Num1 MOD Num2
● Num1 is overwritten by Num2 (moved to the front – compared to diagram)
● Num2 is overwritten by Remain (moved to the front – compared to diagram)
The loop terminates if the remainder is equal to zero.
FORM EVENTS
You also learnt about the OnCreate event in Chapter 4. The OnCreate event is the first event that is
activated when when the application is opened. The OnCreate event is only executed once. This makes
it the perfect event for initialising variables. Another option to initialise variables using the events that
activate when your program is opened the first time is to use the OnShow event.
EVENT DESCRIPTION
OnShow In the sequence of execution, the OnShow event activates after the OnCreate event.
Beyond this, it will be activated each time the form is made visible. This is useful if you
are creating an application with multiple forms.
end;
● For example, you can initialise the variables that you want to use.
procedure TForm1.FormShow (Sender: TObject); Remember!
begin
iCounter := 0; If you want variables to be
sName := ''; accessible from any event,
bIsReady := False; they must be declared
end; globally.
No matter which technique you use, make sure that you initialise all variables before using them in
calculations!
Activity 7.22
Open the Consolidation Activity no. 17, Numbers_p, that you worked on in Chapter 4. This activity required you to play
with numbers. The variable iAnswer was declared many times.
7.22.1 Improve this program by removing unnecessary repetitions and declaring some global variables.
7.22.2 Initialise all variables that will hold the results of a calculation.
7.10 Timers
Up to now, you have been working with loops created in your code. These loops
try to complete the statements inside the loop as quickly as possible. This is great
if you want your program to finish as quickly as possible, but it is not good if you,
for example, are using the loop to control the movement of an object in a game.
When you want to control movement, you need a loop that will always run at
exactly the same speed.
Delphi allows you to create a loop like this using the TTimer component. To add
a TTimer component on a form select TTimer from System in the Tool Palette and
place on the form.
Remember!
It is useful to control visual
The timer component is a non-visual component. You can see the timer aspects of the GUI.
component as an icon in design view. When the program executes, the timer
component is not visible.
The OnTimer event is the only event that the Timer component responds to. You
can then use the OnTimer event to create code that runs when the timer triggers.
Since the code inside the OnTimer event will repeat every few milliseconds, this
works in the same way as a loop. The only difference is that you can control how
quickly the loop repeats.
Just like with loops, the code in the timer’s event will continue running until you
tell it to stop. This can be done by disabling the timer component.
To see how a timer is used, work through the following examples and guided
activities.
For this project, you will create a simple animated game in which a ball bounces around the screen until you click on
it. To do this:
1. Create a new BouncyBall_p project and save it in a folder called 07 – Bouncy Ball.
2. Add a TCircle component from the Shapes list to your user interface.
3. Change the height of the form to 500 and the width to 650.
4. Change the height and width of the circle to 50. Your UI should now look as follows:
The vertical position of the ball is determined by the shape’s Top property. This property tells your shape how
many pixels there should be from the top of the form to the top of the shape. By systematically increasing or
decreasing this value, you can cause the shape to move down or up. Since both iVerticalDirection is equal to 1,
the code above will increase the ball’s Top property by 1 every 5 milliseconds. This will move the ball 1 pixel
away from the top of the window every 5 milliseconds.
11. Save and test your application. The moment the program opens, you should see your ball starting to fall!
12. To cause your ball to bounce, add the following code to your event.
Remember, the ball has a height of 50 pixels while the form has a height of 500 pixels. This means that, when
the ball’s Top property is at 450 pixels, the bottom of the ball is touching the bottom of the form, since
450 + 50 = 500. The moment this happens, the conditional statement becomes true and the vertical direction
changes from positive to negative. This, in turn, causes the ball to start moving upwards.
Unfortunately, you will now see the ball move up until it is out of the screen. To fix this:
13. Update the condition in your timer event so that it change vertical direction whenever the Top property is larger
than 450 or smaller than 0. With this change, the ball’s direction will become positive again once it reaches the
top of the screen.
14. Save and test your application. The ball should now bounce up and down in your application!
Awesome! You have just animated a moving ball using a timer event. In the next guided activity, you will
move the ball sideways and stop the timer when you click on the ball.
In the previous example, you created a bouncing ball game that caused a ball to bounce up and down in window. In this
guided activity, you need to complete the game by completing the following tasks:
7.3.1 Inside the OnTimer event, increase the ball’s Left property by the
value of iHorizontalMovement. This changes the number of pixels Did you know
from the left of the form to the left of the shape.
Changing the starting
7.3.2 If the ball’s Left property is larger than 600 or smaller than 0, multiply values to 10 makes the
iHorizontalMovement by -1. This will change the direction of the ball’s game very difficult!
horizontal movement.
7.3.3 Create a label with a large font in the middle of the form.
7.3.4 Create a global iTime variable and set its value equal to 0.
7.3.5 Increase the value of iTime by 1 in the OnTimer event and display its value in the label.
7.3.6 Create an OnClick event for the ball shape.
7.3.7 Inside the OnClick event, change the timer’s Enabled
property to False if it is True, and to True if it is False. This
allows you to start and stop the ball game by clicking on
the ball.
7.3.8 Inside the OnClick event, reset the value of iTime to 0.
7.3.9 Save and test your application.
7.3.10 You can increase the ball speed by increasing the starting
values of iHorizontalDirection and iVerticalDirection.
Once your improvements are done, you will have created your first, fully functional game. Well done! If you
are interested in creating your own games, the next two years will teach you many techniques that will help
you to create new games.
What you may not know, is that this is actually a hidden game that you can activate by pressing the up
arrow on your keyboard. This activates the Jumping Dinosaur game in which you are in charge of a
dinosaur that needs to jump over (or duck under) oncoming obstacles.
Keeping the bouncing ball game you previously created in mind, develop an algorithm for each of
the following:
1. Repeatedly moving the same cactus from the right side of the screen to the left.
2. Jumping and landing with a dinosaur.
When creating the pseudocode, think carefully about the following questions:
● How will you move the cactus from the right to the left?
● How will the cactus know when it reaches the left of the screen?
● What will you do once the cactus reaches the left of the screen?
● How will you move the dinosaur up when it jumps?
● How will you stop the dinosaur from jumping too high?
● How will you move the dinosaur back to the ground?
● How will the dinosaur know when it has reached the ground?
● What will happen once the dinosaur reaches the ground?
In this user interface, the timer has an interval of 10, while the height and width of the items are given in the
table below.
Cactus movement
imgCactus.Left := imgCactus.Left – iSpeed;
if imgCactus.Left <= -48 then
imgCactus.Left := 640;
This code allows the same cactus to repeatedly appear from the right of the window, by moving your cactus to
the right of the window once it disappears from the left of the window.
4. Save and test your application. You should now see the cactus moving across the screen.
5. In the OnTimer event, decrease the Top property of the dinosaur by the value of iJumpSpeed.
Remember, iJumpSpeed starts with a value of 0. As long as the value is 0, this code will not change the
dinosaur’s position. However, as soon as iJumpSpeed has a positive value, this line will cause the dinosaur to
move upwards. If iJumpSpeed has a negative value, this will cause the dinosaur to drop down.
6. In the OnClick event for the [Jump] button, set the value of iJumpSpeed to 14. Since this value is negative, it will
cause your dinosaur to jump whenever you click on the [Jump] button.
7. In the OnTimer event, create a conditional statement that checks if the dinosaur is in the air. The dinosaur is in
the air whenever its Top position is smaller than 100.
8. Inside the conditional statement, decrease the value of iJumpSpeed by iDropSpeed. This will cause your
dinosaur to move upwards more slowly (and eventually fall downwards) each time the timer activates.
9. Using an ELSE-statement, set the dinosaur’s Top position to 100 and iJumpSpeed to 0 when the dinosaur is not
in the air. The full conditional statement is given below.
Conditional statement
if imgDino.Top > 100 then
iJumpSpeed := iJumpSpeed + iDropSpeed
else
begin
imgDino.Top := 100;
iJumpSpeed := 0;
end;
In real life, whenever you jump, you start by moving upwards at a high speed. However, for every second you are
in the air, you decelerate. This deceleration eventually causes you to fall back down to the ground. Once you
land on the ground, you stop decelerating again. The code from the Jumping Dino game works in the same way.
Every time the timer activates, it checks if the dinosaur is in the air. If the dinosaur is in the air, it decreases the
dinosaur’s jumping speed by iDropSpeed until the dinosaur starts falling. Once the dinosaur hits the ground (that
is, once the Top property is smaller than 100), the jumpspeed is reset to 0.
10. Save and test your application. The dinosaur should now jump whenever you press the [Jump] button.
Awesome! In this application you combined real-life physics with loops to create an interactive game.
To do this, you had to use all the techniques you have learned so far.
All of these improvements are possible using the techniques you have learned so far!
Activity 7.23
REPETITION – LOOPS
Begin
Begin
Start Begin
Start Start
Instruction to Instruction to
iCount <= 10 be repeated be repeated
False False
True False
Instruction to iCount ← iCount + 0.5 iCount ← iCount + 0.5 C
be repeated
STRUCTURES WITH …
ListBox, ComboBox, RadioGroup box components (LCR) with important properties & methods listed
PROPERTY / METHOD LISTBOX COMBO BOX RADIO GROUP BOX
ItemIndex
Columns
Items
Sorted
TabWidth
Items.Add()
IndexOf()
SaveToFile()
LoadFromFile()
Main Purpose of respective LCR-components
● ListBox mainly used for listing tabular data
● Combo & Radio group boxes are mainly for selection purposes
In most programming languages, including Delphi, there are three types of loops that can be used:
● FOR-loop ● WHILE-loop ● REPEAT-loop
These loops generally do the same thing: They repeat several instructions until some condition is met.
However, they differ in how they decide when to start and stop the loops. The table below describes the
three loops and highlights the differences between the loops.
For X := A to B do
// A single Instruction
Write down how many times the ‘single instruction’ will be executed if:
a. A ← 10 B ← 20
b. A ← 15 B ← 10
c. A ← 12 B ← 12
6. The following source code for a loop is given:
Which statements are true and correct and which are false?
a. The integer iNum ends with a value of 98.
b. The while-loop iterates endlessly.
c. The while-loop never executes.
d. iNum may not be changed inside the loop.
7. The following code demonstrates a REPEAT-UNTIL loop:
Repeat
iNum := Random(51) * 2 + 50;
Until (iNum = 51);
8. Go back to example 7.10. Complete the trace table if the two numbers 6 and 15 were exchanged.
9. Write a Delphi application: Save your project as ReverseString_p in a folder named 07 – Reverse String.
The application must accept a small sentence, like: ‘Grade 10 pupil’ and has to reverse the string, so that the
first letter is capital again and the last letter changed to a small letter, like: ‘Lipup 01 edarg’.
Hint: Use the Upcase function to convert a character to uppercase, and use the Lowercase function to convert a
character to lowercase.
10. The program in the 07 – Error Data File folder is meant to help a person keep his cellphone safe. The program
should do the following:
● Generate a new UserName as follows:
The user enters his name in the edtName component.
When btnNewUserName is clicked the name is changed by replacing every vowel in the name with a
random number between 0 and 9. The numbers are then added and the sum of the random numbers is
added to the new UserName.
The name typed into the edit box and the newly generated user name are displayed in the memo
component.
● Generate a password based on the user’s cellphone number as follows:
The user enters the cell phone number in the edtCell component.
When the btnPassword is clicked the cellphone number is converted to a password by replacing the
numbers 3,6,7 and 9 with the characters %,*,@,#, respectively.
Display the password in the memo component.
a. This program does not work properly. Run the program with your name and cell number and try to identify
the errors.
b. Draw a trace table for each of the two procedures to identify the errors made in the program.
c. Apply the corrections needed to fix the identified errors.
11. Write a Delphi application. Save the project as VowelsCount_p in a folder named 07 – Vowels Count.
This application accepts any small sentence and counts the number of vowels as shown in the image to the
right. Display the total number of vowels.
12. Write a Delphi application. Save the project as ExchangeCalculator_p in a folder named 07 – Currency Converter.
This Delphi application must accept any amount in Rand,
which is then converted into the selected currency. A list of
the top 10 currencies exchange rates has been provided
(2018 September). A possible interface is given below.
In September 2018 the exchange rate defined that R 3 000.00 would be converted to $ 208.82. Write a Delphi
application that can convert to at least five other top currencies as illustrated.
13. a. Write a Delphi application. Save the project as MoveBall_p in a folder named 07 – Moving Soccer Ball
Version A: Pick any single bitmap image from the five provided to you by the teacher.
Follow the example interface that has two bitmap buttons.
Each button will move the ball 20 small steps either to the right or then to the left.
Load all pictures: lawn and soccer ball in design-time.
Take note
To display the ball as a round object on the ‘lawn’ switch on the property Transparent from the TImage
object where you load the ball. You could use the Sleep() method, which delays the execution of your
application in units of milliseconds, for example: Sleep(500) will pause your application for half a
second before it goes on.
b. Write a Delphi application. Save the project as RollBall_p in a folder named 07 – Rolling Soccer Ball
Five bitmap images will given to you by the teacher. As you move from one image to the next you can observe
that the ball ‘turned’ a few degrees. Quickly loading the balls one after the other will give you the illusion of a
rolling ball.
The “ball” is delayed by this number of The “ball” is moved by THIS number of
milliseconds, before moving on pixels (left or right)
Take note
Each time the ball moves to its next position it also changes to the follow-up image or previous image
(depending whether we move right or left), to keep up the rolling illusion! This time images are loaded
during runtime.
14. Write the following Delphi application. Save the project as Library_p in a folder named 07 – Library.
a. Design an interface like the one displayed. Make sure that component names are descriptive. The
application gathers information of borrowed books from Grade 10 to 12 learners.
b. Validate data input for all three items: Learner name, grade selected, and number of books borrowed. If any
input is missing, inform the user with: ‘First complete data entry!’ and do not add any incomplete data.
c. The [Reset Single Entry] button clears the ‘Learner Name’ field, unselects any grade and resets the combo
box for a new selection.
d. The [Finalise Report] button adds the summary at the bottom, for example, Total Learners, and so on.
The next three exercises are based on the same tab delimited file: Grd10Term1.txt.
Each row represents a learner’s Surname, First name and mark, respectively.
15. Create a project as MarkDataA_p and save it in the folder named 07 – Mark Data A.
a. Read the text file data into the ListBox when the [Read Data] button is clicked.
b. Display the total of all the marks when the [Total Marks] button is clicked.
c. Display the total number of learners in the list as illustrated.
d. Calculate and display the term 1 average mark correct to one decimal place.
e. Add the result of the average to the bottom of the list as illustrated.
16. Write the following Delphi application. Save the project as MarkDataB_p in a folder named 07 – Mark Data B.
This application reads the same file as used in question 15. BUT this time the data file is saved inside a subfolder
named Data.
When the [Add Symbol] button is clicked, the symbol achieved by each learner must be determined and
displayed as illustrated. Symbols are allocated as follows:
80–100% –> A
70–79 % –> B
60–69 % –> C
50–59 % –> D
40–49 % –> E
Otherwise –> F
b. Next the user must be able to click on one of the symbols listed. An OnClick-event for the RadioGroup box
must be programmed to extract all the learners that achieved the selected symbol. These learners are
displayed on the ListBox on the right. The header of that ListBox must change accordingly.
c. Save and close the project.
CHAPTER
STRING MANIPULATION
8
CHAPTER UNITS
Unit 8.1 Combining strings and determining the length of a string
Unit 8.2 Formatting characters
Unit 8.3 Scrolling through a string
Unit 8.4 Manipulating strings
Learning outcomes
At the end of this chapter, you should be able to:
● explain the concept of string manipulation
● scroll through a string
● search for a character in a string.
● change a string
● build a string.
INTRODUCTION
Often data is encoded into a string. Strings are variables that are made up of a
sequence of letters, numbers and symbols. One example of a string is your South
African identity number. Your date of birth and gender are just two of the data
items encoded into your ID number.
In this chapter you will learn how multiple small strings can be combined into a
single large string, or one string can be broken into multiple smaller strings. You
will learn how to find the position of one character inside a string and replace all
the characters of one type with another. You will also learn how to delete text from
strings and insert text into strings.
In every chapter so far, you have been using strings to display output with
appropriate messages. For example:
In this example:
● the MemoBox component displays strings
● two strings are displayed: ‘The sum is: ‘ and IntToStr(iSum)
COMBINING STRINGS
To combine strings, we use the following syntax:
This syntax is straightforward – you simply add all the strings together using the
+ operator:
In the example above, we could also have combined the two strings before
displaying them. For example:
You can combine any number of strings. However, doing so needs careful
consideration. You need to consider things such as spacing between strings,
whether strings should be displayed on different lines or in columns. For example,
imagine that you have a list of first names and surnames and you want to use to
create a new list in which the name and surname are combined. You might write
the following code:
However, when you display string sName1 and sName2, you realise that the
output is displayed without a space between the name and surname!
Take note
A space is indicated as follows: An empty string is indicated as follows:
● Type a single quote ‘ ● Type a single quote ‘ followed
● Press the space bar once immediately by another single quote’
● Type another single quote ‘ ● ‘’
● ‘‘
This problem is very common since most strings are not saved with a space at
the end. So, before you combine any strings, ask yourself if your combined result
will have the correct spacing before running the application.
Example 8.2
sName := 'John';
iMark := 78
To display the learner’s name and mark in the format: John’s mark is 78
You can count the numbers of characters in a string using the Length function. It
will return the number of characters in a string, for example:
ilen := length('Delphi’);
ShowMessage('The length of your name is:
'+IntToStr(length(sName)));
TERM 3 I CHAPTER 8 STRING MANIPULATION I UNIT 8.1 Combining strings and determining the length of a string 209
After struggling to write a nice birthday message on a card for a friend, you decide to create a program that will
automatically generate birthday cards with beautiful messages for your friends. With some online research, you
identify five birthday messages that you can place on your cards:
● ‘Count your life by smiles, not tears. Count your age by friends, not years. Happy birthday, <NAME>!’
● ‘May your Facebook wall be filled with messages from people you never
talk to. Happy birthday, <NAME>!’
● ‘You are only young once, but you can be immature for a lifetime. Take note
Happy birthday, <NAME>!’
● ‘From good friends and true, from old friends and new, may good luck go <Name> refers to the
with you and happiness too! Happy birthday <NAME>!’ name of a friend that you
● ‘I hope all your birthday wishes and dreams come true. are sending a message to.
Happy birthday, <NAME>!’
The program must prompt for your friend’s name and randomly select one of the five messages to generate a
birthday card.
1. Open the BestBirthdayCard_p project from the 08 – Best Birthday Card folder. If you wish to, you can change
the fonts and colours to something you like.
end;
3. Save and run your application. You can click the [Generate] button multiple times to create different cards.
TERM 3 I CHAPTER 8 STRING MANIPULATION I UNIT 8.1 Combining strings and determining the length of a string 211
To create the OnClick procedure for the mathematical operator buttons, you first need to consider the workflow of a
normal calculator: With a normal calculator, you start by entering a number. Once the number has been entered, you
click on one of the mathematical operators. This stores the number that you have entered in memory and allows you
to enter a new number. When you are done entering the second number, you can press the equals sign to calculate a
solution.
The first line will convert the string from the lblValue label to a real number and store it in the global variable
rStoredNumber. Next, the code will store the type of mathematical operator being used in a global variable.
The lblValue label is set to an empty string.Finally, it will show the calculation being completed in the
Calculation label at the top of the calculator.
8.1.4 Create similar OnClick events for the other mathematical operators, only changing the value stored in the
sOperator variable.
It is starting to look good! The only thing left to do is create an equals button event. This will be done in
the next activity.
The final step of your calculator program is to add, subtract, multiply or divide the value stored in the rStoredNumber
variable with the value shown on the lblValue label.
To do this:
8.2.1 Open the AdvancedCalculator_p project.
8.2.2 Create an OnClick event for the equals to (=) button:
● Create two local variables rCurrentNumber and rTotal.
● Store the value in lblValue in rCurrentNumber:
rCurrentNumber := FloatToStr(lblValue.Caption);
● Add the contents of rStoredNumber, sOperator and rCurrentNumber and store the value in lblCalculation:
This will store the current value in a variable rCurrentNumber and update the calculation string. To ensure the
correct operator is used, you will need to use conditional statements.
8.2.3 Create conditional statements that calculate the value of rTotal based on the operator stored in sOperator.
For example, you could create the following IF-THEN-statement for the plus operator:
if-then statement
if sOperator = '+' then
rTotal := rStoredNumber + rCurrentNumber;
8.2.4 Convert rTotal to a string and assign it to the lblValue.Caption property. Once done, your procedure should
look as follows.
BEGIN
rCurrentNumber := StrToFloat(lblValue.Text);
lblCalculation.Caption := FloatToStr(rStoredNumber) + ' ' +
sOperator + ' ' + FloatToStr(rCurrentNumber);
lblValue.Caption := FloatToStr(rTotal);
END;
TERM 3 I CHAPTER 8 STRING MANIPULATION I UNIT 8.1 Combining strings and determining the length of a string 213
8.2.5 Instead of four separate IF-THEN statements you can use a CASE-statement:
case sOperator of
‘+’ : rTotal := rStoredNumber + rCurrentNumber;
‘-‘ : rTotal := rStoredNumber – rCurrentNumber;
‘*’ : rTotal := rStoredNumber * rCurrentNumber;
‘/’ : rTotal := rStoredNumber / rCurrentNumber;
end;
8.2.6 Save your program and test it. You should now be able to use it like a normal calculator.
Congratulations on creating a real calculator! For this program, you needed to create a large number of
events, local and global variables of different types, as well as combine strings and use conditional
statements to complete calculations. By combining everything you have learned so far, you were able to
create a fully functional program!
For Enrichment Creating an executable file for your advanced calculator project
To celebrate completing your calculator application, you can convert it to an executable file which can be used on any
computer. To do this:
1. Open the Project menu at the top of RAD Studio.
2. From the menu, select Project and click on the Build All Projects button.
TERM 3 I CHAPTER 8 STRING MANIPULATION I UNIT 8.1 Combining strings and determining the length of a string 215
8.1.1 Create a [Magic Number] button by dividing a random number between 50 and
100 by your age and multiplying the result with 0.93.
8.1.2 Display information from various inputs as a single string.
8.1.3 Complete the OnClick event for the [Display] button by following the
guidelines below:
Create a single string that displays the name and surname on the first line. On
the next line, display the word ‘Favourites’ followed by a colon, and the name of
the song, with the word ‘Song’ in brackets. Then display the colour with the word
‘Colour’ in brackets. On the last line, display the magic number and the word
‘Magic’ in square brackets.
You have already learnt how to format output using the FloatToStrF function. In this unit you will use a
control string to format strings. A control string is a sequence of one or more control characters, each of
which consists of the # symbol followed by an integer constant. The integer constant denotes the
corresponding ASCII character.
For now we will use three formatting characters. That is: #9 (tab character), #10 (line Feed) and #13
(Carriage Return )
One way to make sure that your line format and spacing is correct, is to use the Return character and the
Tab character. Look at the examples in the table below.
Notes:
● You can use the #9 and #13 formatting characters to format strings.
● #9, #10 and #13 do NOT appear in quotes
● To combine strings with formatting characters, you use the + operator
● Sometimes, it will be necessary to use more than one tab character to align strings of different
lengths. To do this, you simply add the #9 character multiple times. For example:
sDisplay := 'Mark1'+#9#9+'71%';
memDisplay.Lines.Add('First Line'+#9#9#9+'Second Line');
● Use #13#10 combination to leave a line in a memo box NOT just #13 as is used in labels:
Mark 1: 80%
Mark 2: 86%
Average: 83%
Thandi, you are excellent in Mathematics
Activity 8.2
Open the Booking_p project from the 08 – Booking folder. Three text files: BookingCode.txt; AmountOwed.txt and
Discount.txt are provided.
Complete this app as follows:
8.2.1 Complete the code for btnLoad to load
the textfiles into the ComboBox
components by using the LoadFromFile
method of the ComboBoxes.
8.2.2 Complete the code for the [Display] button by building one string to display the values selected on each of
the ComboBox components in columns as shown in the screenshot alongside.
Var sName:string;
sSurname:String[15];
Notes
● the variable sName can hold up to 255 characters
● the variable sSurname can hold up to 15 characters. If you assign a string with more than 15
characters to sSurname, then only the first 15 characters of the string will be assigned.
Each character in a string has a position with the first character of the string starting at position 1.
For example, in the string sString:= ‘I LOVE CODING’
CHARACTER I L O V E C O D I N G
POSITION 1 2 3 4 5 6 7 8 9 10 11 12 13
variableName [position]
● the string variableName followed by the position of the character in square brackets[]
● for example, sString[5] will refer to character ‘V’ and sString[10] will refer to character ‘D’ in the
table above.
Example 8.4
sName[n] is also a variable of type Char and represents a single character. The following code snippets
show how this can be done.
The position variable also known as the index can be used as a loop variable in a FOR-loop. This will allow
you to scroll through the string as follows:
Display each character of sName on a new line in a memo component memOutput. Use the Courier New font.
sName:=’THANDI’;
The Output must be:
T
H
A
N
D
I
This program must display one character at a time from string ‘Thandi’ one below the other starting from the
first character.
8.4.1 Open the ExtractingCharacters_p project from the 08 – Extracting Characters folder.
TERM 3 I CHAPTER 8 STRING MANIPULATION I UNIT 8.3 Scrolling through a string 221
8.4.2 Create an OnClick event for the [Extract Character from the beginning] button and do the following:
a. Declare two local variables sName and iIndex. sName will hold the name ‘THANDI’, and iIndex will hold
the position of a character in the string sName.
b. Clear the memDisplay memo box.
c. Assign ‘THANDI’ to sName.
d. Loop from first character position 1 to the position of the last character (length(sName)).
e. Display the character at each position in sName in the memDisplay
procedure TfrmExtractingCharacters.
btnExtractFroBeginClick(Sender: TObject);
var
sName: String;
iIndex: Integer;
begin
sName := 'THANDI';
memDisplay.Lines.Clear;
for iIndex := 1 to Length(sName) do
begin
memDisplay.Lines.Add(sName[iIndex]);
end;
end;
8.4.4 Create an OnClick event for the [Extract Characters from the End] button to extract the characters from
sName and display the output is memDisplay memo component as follows:
I
D
N
A
H
T
a. Declare two local variables sName and iIndex. sName will hold the name ‘THANDI’ and iIndex will hold
the position of a character in the string sName.
b. Assign ‘THANDI’ to sName.
c. Clear the memDisplay memo box.
d. Loop from last character position (length(sName) down to the first character position 1.
procedure TfrmExtractingCharacters.
btnExtractFromEndClick(Sender: TObject);
var sName:string;
iIndex:Integer;
begin
memDisplay.Lines.Clear;
sName := 'THANDI';
for iIndex := Length(sName)downto 1 do
memDisplay.Lines.Add(sName[iIndex]);
end;
8.4.5 Save and run the program and click on the [Extract Characters from the End] button.
Being able to access an individual character in a string allows you to use a character from a string in
different ways or to manipulate the string by replacing, deleting or inserting a character. You can:
● create conditional statements based on specific characters.
● copy certain characters.
● compare specific characters in different strings.
● assign new values to individual characters.
● delete individual characters.
Activity 8.3
8.3.1 Given:
TERM 3 I CHAPTER 8 STRING MANIPULATION I UNIT 8.3 Scrolling through a string 223
a. H b. H W
e e o
l l r
l l l
o o d
Write an algorithm in pseudocode to display any text and width input, as Rectangular Text. Pay careful
attention to the position variable when the characters are concatenated to form a line and don’t forget to
re-initialise the line variable to an empty string.
TERM 3 I CHAPTER 8 STRING MANIPULATION I UNIT 8.3 Scrolling through a string 225
Write a program that will display the user input with each character followed by a hyphen.
If the input is: groovy The output must be: g-r-o-o-v-y-
OCR software O-C-R- -s-o-f-t-w-a-r-e-
17 Church Str 1-7- -C-h-u-r-c-h- -S-t-r-
R 100.00 R-1-0-0-.-0-0-
Note: spaces, digits, punctuation symbols are all characters.
IPO:
Input Processing Output The Memo box component’s Lines.
Add(s) method will displays in one line.
word Line ← ‘’ Line
The for-loop loops through the word
For k ← 1 to Length(word)
one character at a time from the first
Line ← Line + word[k] + to the last character.
‘-‘
The line g-r-o-o-v-y- must be prepared
endfor before it can be displayed.
Component: Component: Line ← Line + word[k] + ‘-‘ , prepares
inputBox Memo box the line, where word[k] is the letter in
groovy at position k.
Delphi code:
var
sWord: String;
k: Integer;
sLine: String;
begin
memOutput.Clear;
Line 1: sWord := InputBox('Question 1','Enter text: ','');
Line 2: sLine := '';
Line 3: for k := 1 to Length(sWord) do
begin
Line 4: sLine := sLine + sWord[k] + '-';
end;
Line 5: redOutput.Lines.Add(sLine);
end;
Activity 8.5
Open the Delphi project CharacterAccess_p in folder 08 – Character Access. Code for
the example as shown alongside, run the program and click question 1.
Input the text, groovy, and confi rm the output, g-r-o-o-v-y-.
8.5.1 Button [Question 1]
Change the program to output g-r-o-o-v-y, without the last hyphen.
The following questions will assist you to find one of many possible
solutions.
a. Must sLine be initialised to ‘’? What if it is initialised to the first
character of sWord?
sLine ← sWord[1];
b. What effect will such a change have on Line 3 and Line 4 in the example code on the previous page?
c. What value must k start with?
d. Will the current order of concatenation work? i.e. sLine + sWord[k] + ‘–‘. If not how will you change it?
8.5.2 For each of the question below, complete the code.
a. Button [Question 2]
Display the word entered by the user in reverse order.
Example: Input: YOLO output: OLOY
TERM 3 I CHAPTER 8 STRING MANIPULATION I UNIT 8.3 Scrolling through a string 227
b. Button [Question 3]
Example:
Line ← “
Input: sentence ← learning to code
Line ← length(sentence)
Output: Line ← ai d
i←1
There are 2 spaces between the i and d. i←i+1
Display Line
Stop
c. Button [Question 4]
Display the word entered with each letter below each other starting from character at position 1.
Example input: CAT output: C
A
T
d. Button [Question 5]
Display the word entered for each letter below each other starting from the last character.
Example input: CAT output: T
A
C
e. Button [Question 6] f. Button [Question 7]
Display the string ‘Hello’ as indicated: Display the string ‘Hello World’ as indicated:
H H W
e e o
l l r
l l l
o o d
Activity 8.6
Create a Delphi project to implement your Rectangular text algorithm. Name the project RectText_p and the unit
RectText_u and save them in a folder named 08 – Rectangular Text.
Provide the interface with the following:
● Labels for width and text.
● Edit boxes for width and text.
● Set the width edit to accept numbers only. The Edit Box for width must be set to receive numbers only.
● A button with the caption ‘Show Rectangular Text’.
● A memo component to display the text. Set the font for the memo to Courier New.
Strings
sName := 'Lundi';
sPhrase := 'I love programming!';
TERM 3 I CHAPTER 8 STRING MANIPULATION I UNIT 8.3 Scrolling through a string 229
Now that you know how to scroll through each character of a string, you can start manipulating the string.
In this unit, you will learn how to do the following:
● find all instances of a specific character.
● change all instances of a character into a different character.
● delete a character from a string.
● insert a character into a string.
● determine the position of a character in a string.
● find a character.
8.6.1 Open the SearchCharacter_p project from the 08 – Find Character folder.
8.6.2 Create an OnClick event for the [Search All Occurrences] button to determine the positions of a search
character in a string:
a. Declare four local variables: sPhrase, cSearch, iIndex and bFlag where sPhrase is the search string,
cSearch is the search character, iIndex will be used as a loop counter and bFlag will be used to
determine whether the search character cSearch is found in the search string sPhrase
var sPhrase:string;
cSearch:char;
iIndex:Integer;
bFlag:Boolean;
memDisplay.Lines.Clear;
c. Set a variable bFlag to FALSE. This variable will be used to determine whether the search character is in
the search string or not.
bFlag := False;
d. Read the search string from the edtPhrase edit box component and assign the value to the sPhrase
variable.
e. Read the search character from the edtSearch edit box and assign the value to the cSearch variable.
Remember that you are reading string data from the edtSearch edit box and therefore cannot assign it
directly to the character variable cSearch. You will get a type mismatch error. To ensure you don’t get an error:
sPhrase := edtPhrase.Text;
cSearch := edtSearch.Text[1];
g. Check whether the character at the loop counter position is equal to the search character cSearch.
If the character at the loop counter position is equal to the search character sSearch then display the
loop counter position. Also set the bFlag variable to true. This indicates that a match has been found.
h. Once the loop is exited, determine whether a match has been found. If a match has not been found, then
display a message ‘Character not found in string’.
if not(bFlag) then
memDisplay.Lines.Add('Character not found in string');
end;
8.6.4 You can also find the FIRST occurrence of a character in a string. Study the code below:
Assume ‘Hello Jo’ will be read for sPhrase in Line 2 and character ‘o’ for cSearch. Trace through the flowchart
using these values.
8.6.5 Open the SearchCharacter_p project. Create an OnClick event for the [Search for First] button to determine
the FIRST occurrence of a search character in a search string.
8.6.6 Save and run the project.
Activity 8.8
8.8.1 Given:
sentence ← ‘I love computer programming’
searchChar ← ‘r’
count ← 0
index ← 1 to length(sentence)
a. What notation do we use to refer to a character in a string? Give an example.
b. Give two Boolean expressions to test for the letter ‘r’ in sentence.
c. Now place one of your Boolean expressions as the test condition of an IF-statement.
d. Give a reason for your choice of Boolean expression in (c).
e. In the body of the IF-statement, provide code to count the number of ‘r’ characters in the sentence.
f. Which character would you use as test character if you had to count the number of words?
g. Write down a test condition for vowels.
h. Describe a test condition that will determine if a character is a consonant in a sentence.
i. Provide Delphi code for your test condition in (h)
8.8.2 Complete the trace table for the algorithm given below.
Line 1 Label ← 'programming'
Line 2 ch ← 'r'
Line 3 for i ← 1 to length(Label) do begin
Line 4 if ch = Label[i] then
Line 5 Display ch + ' found in position ' + i
newline
end if
end for
var
Line 1: sIdNumber: String;
Line 2: sLine: String;
begin
Line 3: redOutput.Clear;
Line 4: sIdNumber := edtIDNumber.Text;
Line 5: if StrToInt(idNumber[7]) >= 5 then
Line 6: redOutput.Lines.Add('Gender: male')
else
Line 7: redOutput.Lines.Add('Gender: female')
end;
Activity 8.9
8.9.4 Complete the algorithm given below by providing the missing pseudocode. The algorithm should accept an
encoded #-delimited string, search for the delimiter and display each data item below each other.
8.9.5 Provide trace tables for your algorithms in 8.9.2 to 8.9.3 above. Trace using the given examples.
Example: Write Delphi code that will count the number of vowels in the text input. To write the Delphi code,
you must have a solution. Writing the Delphi code is a translation of your solution that can be in the form of
pseudocode or a flowchart.
The IPO table will assist you in formulating a solution because it breaks up the task into three smaller tasks
focussing on input, processing and output.
If the input is ‘Count the number of vowels’ then the output is 8.
Here is the IPO table:
Component: Component:
inputBox MemoBox
Take note
The algorithm loops through the text and increases count if a vowel is found.
Note how the IN operator is used to check if the character at position k is a vowel.
Some of the questions you can ask when translating the solution into Delphi code includes:
● What are the variables and how are they declared?
● What are the data types for these variables?
● Where must count be initialised? Inside or outside the loop?
● How do I implement the for-loop?
var
sText: String;
k: Integer;
iCount: integer;
begin
redOutput.Clear;
Line 1: sText := InputBox('Question 1','Enter text: ','');
Line 2: iCount := 0;
Line 3: for k := 1 to Length(sText) do begin
Line 4: if sText[k] in ['a','e','i','o','u','A','E','I','O','U'] then
Line 5: iCount := iCount + 1;
end;
Line 6: redOutput.Lines.Add('The text has '+IntToStr(icount)+'vowels');
end;
Activity 8.10
27/06/2018 True
is:
Output Item Item ← Item + Text[k]
Injured Text[k] = #
False
Item ← “ k←k+1
Activity 8.11
Open the Delphi project CharFrequency_p located in the 08 – Find Character Frequency folder. The program
determines how often the selected letter is found in a paragraph. The result is displayed as a percentage of the total
number of characters in the paragraph.
memOutput
lstAlphabet
VARIABLE PURPOSE
sText Represents the paragraph
k Loop index
cLetter Selected letter
iTotal Total number of characters in Text
iCount How many times the Letter is found in Text
rFrequency The percentage of Letter in Text
8.11.1 Write down a Delphi code statement or expression for each of the following:
a. Read the selected letter from the list box.
b. Determine the total number of characters in the paragraph.
c. Initialise iCount to zero.
d. A FOR-loop to scroll from position 1 to the length of the paragraph.
e. Test if the character at the current position of the loop index is equal to the selected letter.
f. Increment iCount.
g. Calculate the frequency using iCount and iTotal.
8.11.2 Use the code in 8.11.1 to complete the code for [Frequency of Selected Letter] button.
Input: a Output: Letter a: 8%
b Letter b: 0%
var sVariable:string;
iPosition:integer;
cChar:char;
begin
…
sVariable[iPosition] := cChar;
…
end;
The value in variable cChar is assigned to the character at position iPosition in the string variable sVariable.
The ‘old’ value in sVariable[iPosition] is overwritten by the value of cChar.
sWord[3] := 'i';
ShowMessage(sWord); // Trick
sWord[1] := 'B';
ShowMessage(sWord); // Brick
This technique can be combined with the technique to search for a character to replace either a specific
character or all instances of a character. The code snippet below shows how all instances of the character
‘o’ are replaced by the character ‘a’.
Write a Delphi program to create a strong password based on the user’s name. Save the project as
StrongPassword_p in a folder named 08 – Strong Password.
Write code for the [Password] button to create a password as follows:
8.12.1 Receive the name of the user by using an Inputbox.
8.12.2 Determine the length of the name. If the name is shorter than eight characters, add as many of the
characters ‘#’, ‘$’, as required to make the length of the string eight.
8.12.3 Replace all the vowels in the word with the letter ‘Q’.
8.12.4 Replace ‘b’, ‘m’, and ‘z’ with the symbol ‘^’.
8.12.5 All other letters remain as they are.
8.12.6 Display the password.
DELETING A CHARACTER
The final two techniques you will learn about both use the same general
algorithm. In the simplest terms, the algorithm works as follows: Did you know
● Store the position of the character you want to delete. There are many different
● Add all characters before this position to a new string called sStart. algorithms that can be
● Add all characters after this position to a new string called sEnd. used to delete or insert
● Set the existing variable equal to start + end. characters. However, the
algorithm discussed in this
This algorithm works by storing all the characters before the deleted section is one of the easiest
character and all the characters after the deleted character in new strings. algorithms to remember
Since neither of these strings contain the deleted character, they can be and use.
combined to form the starting word without the deleted character.
Figure 8.2: To delete a character, you can recreate the string without the character
For this project, you will allow the user to delete any character from a string. To do this:
1. Open DeleteAndInsert_p Project from the 08 – Deleter and Inserter folder.
f. If sPhrase:=’Peter Pan Outfit’ and the position iPosition of the character that must be deleted is 8, then
once the loop is executed sStart will be assigned the value ‘Peter P’ and sEnd will be assigned the value
‘n Outfit’
g. Join sStart and sEnd and assign it to sPhrase.
3. Save and run the project.
4. Write code for the OnClick event of the [Insert] button to insert a character in the position where you deleted a
character. Look at the example on the next page before attempting this.
INSERTING A CHARACTER/S
You can insert a character/s in a string at a given position.
Given:
sEnd := '';
for iCount := 10 to length(sPhrase) do
sEnd := sEnd + sPhrase[iCount];
● Join sStart, the new character to insert and the sEnd strings and assign to sPhrase:
sPhrase := sStart+’B’+sEnd;
Insert event
procedure TfrmDeleterAndInserter.btnInsertClick(Sender: TObject);
var
sPhrase, sStart, sEnd, sChar : String;
i, iPosition : Integer;
begin
sStart := '';
sEnd := '';
sPhrase := memPhrase.Text;
sChar := edtCharacter.Text;
iPosition := StrToInt(edtPosition.Text);
for i := 1 to Length(sPhrase) do
begin
if i < iPosition then
sStart := sStart + sPhrase[i];
For enrichment
The setLength function can be used to change the length of a string.
For example:
setLength (sText, 6)
This sets the new length of sText to 6 characters. If the original length is more than 6 the characters from
position 7 onwards will no longer be part of the string. If the original length is less than 6, say 4 then space
for 2 more characters are reserved but not initialised. The two extra spaces contains garbage and can result
in errors. To avoid, this always initialise the extra space. Fill it with the space-character.
8.13.1 Use the user interface below to complete the following tasks. Open the Activities_p project from the
08 - String Manipulation folder. Each of the buttons should be used for one of the questions.
a. Show how long your name is.
b. Insert the dash symbol (-) between each letter of
your surname.
c. Replace each vowel in your surname with the
asterisk character (*).
d. Show the position of all the ‘s’ characters in the
word ‘Mississippi’.
e. Delete the third character of any word entered
into the text box.
8.13.2 Open the program SmartphoneLogin_p from the 08 – Smartphone Login folder. Using this application,
update the ‘forgotten password’ clue so that it shows three randomly selected letters from your password.
Activity 8.14
8.14.1 Given
Text ← ‘—abcd—
POSITION 1 2 3 4 5 6 7 8
TEXT - - a b c d - -
Provide an algorithm to move the characters in position 3 to 6:
a. two places to the right b. two places to the left.
POSITION 1 2 3 4 5 6 7 8
TEXT a b c d - - - -
- - - - a b c d
In each case avoid assigning characters beyond the string boundary. The length of text must remain eight
characters long.
8.14.2 Given the string:
Word ← ‘characters’
Provide Delphi statements to do the following in order:
a. replace the letter ‘e’ with a letter ‘o’.
b. Given:
Text ← ‘ming_ ’,
Add the contents of the variable Text at position 5 in valuable Word.
8.14.3 Provide an algorithm to show how four characters are deleted from a 10-character string starting at position 2.
a. Write a pseudocode algorithm that will replace a character at any position with a new character in a
string.
b. Provide a flowchart to replace all occurrences of a user selected character with a second character
provided by the user.
c. Now open the incomplete Delphi project, ReplaceChars_p located in the 08 – Replace Characters folder.
Provide code for the [Replace Char] button to implement your algorithm in a).
●
Provide code for the [Replace All] Button according to your solution in b).
●
8.15.2 Open the project MoveCharsRight_p from the 08 – Move Characters Right folder.
8.15.3 Open the project MoveCharsLeft_p from the 08 – Move Characters Left folder.
a. Provide code for the button [Move 1 char Left] to move the character from the position indicated to the
number of places to the left.
b. Button [Move substring Left] moves consecutive characters between from and to positions to the left.
Activity 8.16
When the game starts Player 1 clicks the [Start Game] button to set the hidden word and enters the word
that must be hidden. The computer randomly selects a character from the hidden word and displays all
occurences of that character and ‘-‘ s for all other characters. Player 2 starts guessing the missing
characters. The computer determines if Player 2’s character is in the word and if found, displays it in the
correct position. This continues until the complete word is displayed.
a. Recreate the word game and in addition provide one improvement, for example, count the number of
guesses.
b. Change the user interface to include your improvement.
8.16.2 In many languages the adjective follows the noun in the sentence structure.
‘Inenekazi ehlihle lingena eholweni’
A word for word translation for this isiXhosa sentence to English becomes:
‘The lady beautiful enters the hall’
The adjective ‘beautiful’ comes after the noun ‘lady’.
Given the sentence and the starting position of the adjective, develop a Delphi program to switch the noun
and adjective around so the sentence reads:
‘The beautiful lady enters the hall’
Open the project NounAdjectiveSwitch_p from the 08 – Noun Adjective Switch folder.
Complete the code for the [Switch Noun and Adjective] button to switch the noun and adjective.
STRING MANIPULATION
A String can consist of any number of
characters. Manipulating a string like
In Delphi multiple small strings can be combined into a single
appending, inserting, replacing and
large string.
deleting one or more characters would
sFirstName := ‘Sharise’; Combining strings require that the computer can access the
and determining individual characters in the string and has
sSurname := ‘Marone’; the length of some way to determine the length of the
a string string.
sName := sFirstName + ‘ ‘ + sSurname; // ‘Sharise Marone’
● sPhrase := ‘I love programming!’;
● iLength := Length(sPhrase); //19
One way to ensure that your spacing is correct when combining string is
to make use of the tab and newline characters.
Outcomes:
● Find all instances of a specific character.
Individual characters in a string can be
● Change all instances of a character into a
accessed as follows: Manipulating different character.
strings
● Delete a character from a string.
VariableName[position of character] ● Insert a character into a string.
● Determine the position of a character in a string
● Finding a character
6. A palindrome is text that reads the same from left to right and right to left, for example, level and 123321.
a. Write a program to determine if a word or number is a palindrome.
9. Upon analysis of large amounts of English text, the frequency of letters are as follows:
e t a o i n s h r d l u c
12.7 9.1 8.2 7.5 7.0 6.7 6.3 6.1 6.0 4.3 4.0 2.8 2.8
m w f y g p b v k x j q z
2.4 2.4 2.2 2.0 2.0 1.9 1.5 1.0 0.8 0.2 0.2 0.1 0.1
These frequencies are used to decrypt code like the Caesar Cypher. Although the letters are substituted the
frequency remains the same.
For this problem we will add a monetary value to groups of letters on the basis that the least frequent letters are
more expensive.
Open the NameValue_p project from the 08 – Name Value folder and complete the program.
The program must accept your full name and calculate the monetary value of your name according to the table
above. Use lowercase letters.
10. Pig Latin is a secret language formed by moving the first letter of a word to the end if the letter is a consonant.
The letters ‘ay’ is then added, for example, if the word is ‘must’, it becomes ‘ustmay’ – ‘m’ moved and ‘ay’
added. Vowels at the beginning are not moved to the end and ‘way’ is simply added at the end.
Write a program that will translate a sentence into Pig Latin. Save the project as PigLatin_p in a folder named
08 – Pig Latin.
11. Open the ScrollingBanners_p project from the 08 – Scrolling Banners folder and complete the program. The
program must allow the user to enter a message. The program must scroll the message as indicated below.
a. Left to right, disappearing on the right and re-appearing on the left. For example:
b. Exiting on the right of the top line and entering on the left of the line below, scrolling along the bottom line
and exiting on the right, finally entering on the left of the top line. For example:
Run the ScrollingBanners_p.exe, enter a message and click the [Start] button to start the scrolling banners.
CHAPTER
PAT PREPARATION
9
CHAPTER UNITS
Unit 9.1 Tools and techniques to create a software solution to a problem
Unit 9.2 A problem solving approach
Unit 9.3 Analysing user interfaces
Learning outcomes
At the end of this chapter, you should be able to:
● explain what problem solving is
● understand how to approach a programming problem
● explain and apply problem solving steps and techniques to a given problem
● use the correct problem-solving tools.
● understand how to use the correct tools, principles and techniques to do the PAT
INTRODUCTION
In Grade 10 you need to complete a programming project called the Practical
Assessment Task (PAT). The PAT is a software development project. You can use
the PAT to demonstrate your programming skills and your understanding of the
connections between the different content areas of solution development that
you have learnt about.
Take note
PROVIDE DISCUSS
● The PAT is a
compulsory component
of the final end-of-year
examination for IT. PROBLEM DESCRIBE
● The PAT counts 25% of
your final mark for IT. It
Discuss the research /
is important that you Provide a brief description of investigation done regarding
the problem you will be the project
produce work of a high solving
standard.
● You need to complete
your PAT before you
start the Grade 10
end-of-year RESEARCH
examination. Not
submitting your PAT or
any part of the PAT, will DESCRIPTION
mean that you will be
awarded a zero (“0”) SOLUTION
for the PAT component
of the examination or
Provide a brief description of
the parts not submitted. the purpose and scope of
your project
PURPOSE
IMPLEMENT
DESIGN
LAYOUT
Figure 9.1: Outputs for the effective use of software design tools and techniques
In this chapter, you will learn how to approach the PAT. You will also learn some
additional skills you could use to enhance your project.
When you want to create a software solution to a problem, there are certain tools and techniques that
support a professional product. There are also certain principles that you need to adhere to, to ensure that
your solution (app) is user-friendly.
GUI COMPONENTS
To ensure that your solution has a professional, user friendly appearance, it is important to plan the
graphical user interface (GUI) and to use the correct components. This year you have learnt to use the
most important components that allowed you to create simple user interface.
We are now going to look at a few other components that would be helpful to enhance your project’s user
interface.
TERM 4 I CHAPTER 9 PAT PREPARATION I UNIT 9.1 Tools and techniques to create a software solution to a problem 255
If you want to store data permanently, then you need to save it to a file.
You have already learnt how to save data to files and read data from files. When saving you use the
Delphi components that work with a list of strings (like the TListBox and TMemo). This is because these
components have built-in methods that allow you to save their items directly to a text file, or to load data
from a text file into the component. This is done using the following two commands.
FUNCTION DESCRIPTION
memName.Lines.SaveToFile('file.txt'); Saves the contents of a memo directly to a file.
lbxName.Items.SaveToFile('file.txt'); Saves the contents of a list box directly to a file.
memName.Lines.LoadFromFile('file.txt'); Loads the contents of a file into a memo.
lbxName.Items.LoadFromFile('file.txt'); Loads the contents of a file into a list box.
The example below shows how these commands can be used to create a simple text editor.
TERM 4 I CHAPTER 9 PAT PREPARATION I UNIT 9.1 Tools and techniques to create a software solution to a problem 257
sFileName := sFileName+'.txt';
7. Run the program, enter the file name, type in the memo component and click on the [Save] button.
8. A text file with the file name that you specified with a .txt extension will be created. The data from the memo
component will be saved in the text file.
This will load the text from the specified filename into your memo component.
10. Save and test your application.
You should be able to create new files or open existing files by using the [Save] and [Load] buttons.
While the technique was used in this application to simply save and load text to a file, it could also be used
with a listbox component.
In this section, you will learn more about each of these tools.
IPO TABLE
For Input, Processing and Output (IPO) tables refer to chapter 4.
After speaking to enough users, the programmer might have an entire list of user
stories. These stories help the programmer to understand the problem and can https://www.youtube.com/
watch?v=tKSUokG3Y0w
be used to focus the programmer’s attention on the most important features.
Figure 9.2: A web application like Trello is good for recording user stories
TERM 4 I CHAPTER 9 PAT PREPARATION I UNIT 9.1 Tools and techniques to create a software solution to a problem 259
For these reasons, most programmers should try to interview some of their users
before starting to program their application. This can be as easy as asking your
mother, your sister and a few of your friends questions about what they would
want from your application and recording their answers.
ACCEPTANCE TESTS
Each user story must have an acceptance test. Acceptance tests are derived
from user stories. In acceptance testing, the product is tested to see if it solves
the problem and meets the project’s requirements. The program either passes
the test or fails. This determines if the program is ready to be officially released
and sold to customers, or if the program needs further development.
PROGRAMMING PRINCIPLES
NAMING CONVENTIONS
Use the naming convention used throughout the book.
DECLARATION OF VARIABLES
In Chapter 2 you learnt how to declare variables both locally and globally.
DATA VALIDATION
You learnt about data validation in Chapter 6.
TERM 4 I CHAPTER 9 PAT PREPARATION I UNIT 9.1 Tools and techniques to create a software solution to a problem 261
Now that you understand what tools and techniques contributes, you can continue exploring a problem-
solving approach that can be used when you complete your PAT.
Problem solving refers to the process through which a solution is found to a problem. Programmers spend
most of their time solving problems, whether it is a small technical problem like a program bug or developing
a software solution for a specific use. For example: Uber is attempting to provide an affordable but flexible
transport solution to people without a car.
In this unit, you will learn more about the techniques used by programmers to solve problems.
The following sections demonstrates how the above steps are used to develop the IT PAT.
PROBLEM
You need to develop a program that encrypts messages using a cipher and decrypts messages using the
same cipher. For example, if you want to send an encrypted message to a user using your application,
that user must be able to use the program to decrypt the message.
You could also have a cipher game where others are challenged to crack the ciphers.
Here are some ideas for developing your own cipher. Using:
● Binary numbers
● ASCII codes /symbols
● Standardised numbers such as ID numbers, ISBN numbers
● Calculations
● Mathematical processes such as check digits, LCM, etc.
● String processes
● Combining aspects of existing ciphers, etc.
Example:
You are one of the learners at IT Academy. The pass rate at this Academy is 60%.
Write a program to display a message “YOU HAVE PASSED” if your mark is 60%
or more.
DEVELOPING A PLAN
You spend hours creating an implementation plan, which might feel like a waste
of time, however in the long run it pays off when you start creating your application.
Rather than struggling to create a massive program that you do not understand,
the implementation plan breaks it into small, manageable tasks that can be
completed systematically. With each completed task and line of code that you
write, you are one step closer to having a working product.
If your evaluation reveals any remaining problems, you can repeat the problem-
solving process, focusing on the new problems.
According to the principles of rapid application development, you should start with the user interface. By
the time you have placed all the elements, boxes and buttons for your application, the only thing left to do
is to code the events. Since there are only a limited number of buttons and interactive elements, there can
only be a limited number of events, which means you can systematically create small parts of your
program, without worrying too much about the big picture.
How do you take the first step and build a user interface? A good way to do this is to analyse existing user
interfaces, especially for applications that are similar to your application, and use their user interfaces as
a starting point. These user interfaces can be analysed in four steps:
● Take a picture of the screens of the user interface
● Break the screens down into their components
● Record how the user interacts with the application
● Draw a map showing how the user can navigate between screens
By analysing existing user interfaces, you will be surprised to see how many small features application
developers add to make their programs easier to use. You will also realise that many UIs that look extremely
complex are actually created using very simple components.
In the next section, you will use the four steps listed above to analyse an existing user interface.
The first step in analysing the application is to record the different screens used by UberEats. The images
below show nine screens from the UberEats app.
TERM 4 I CHAPTER 9 PAT PREPARATION I UNIT 9.3 Analysing user interfaces 265
By analysing these screens, you can learn how they are created.
Label
Edit
Image Components
on a scrollable panel
Icons on a panel
Broken down like this, the screen is not too difficult to recreate. In fact, you know how to create almost all
the elements on the screen already! Creating a similar screen for your own user interface is therefore
simply a matter of placing all the components in the correct positions.
For example, looking at the Search screen from the previous step, there are three ways for users to
interact with this screen:
● They can enter a search query at the top of the screen
● They can click on one of the category images
● They can navigate to a different screen using the panel at the bottom.
TERM 4 I CHAPTER 9 PAT PREPARATION I UNIT 9.3 Analysing user interfaces 267
What happens when users click on one of the categories? In UberEats, the
program simply searches for the category name, returning the same results as if
the user entered the category name. This means the code for these buttons is
easy to create, since it can reuse the search algorithm code created already.
When the users click on one of the navigation buttons at the bottom of the
screen, the program simply swaps to the selected screen. Once these screens
have been created, coding the buttons so that they swap to the correct screen is
easy!
Registered No Sign-up
Yes
Search Orders
Restaurant
Meal
Checkout
Close App
Now that you understand how the UberEats user interface works, you can use
the relevant concepts in your own programs. The more user interfaces you
analyse, the more ideas you will have for your own programs!
TERM 4 I CHAPTER 9 PAT PREPARATION I UNIT 9.3 Analysing user interfaces 269
PAT PREPARATION
YOUR SOFTWARE DEVELOPMENT PROJECT
7. Click on the [Download Now] button to download the RAD Studio install file.
Congratulations, you have just downloaded the RAD Studio installer! You are now
ready to begin installing RAD Studio.
Take note
The exact layout may
change over time, so follow
the prompts on the screen
if the layout is different to
what is being shown here.
5. Select the serial number from the email and press CTRL + C to copy it to your
clipboard.
6. When the Embarcadero Product Registration window opens, select the Serial
Number textbox and press CTRL + V on your keyboard. You should now see the
serial number in the textbox.
9. Click on the [Install] button to begin downloading and installing the application.
Once the installation is complete, you can start using RAD Studio!
Congratulations, you have just installed Embarcadero’s RAD Studio! For the rest
of the year, you will use this application to code programs and games!
In 1963, the American Standards Association published a table which linked 127 different letters and symbols
to numbers. This table was called the ASCII table, which is short for the American Standard Code for Information
Interchange.
With ASCII, the first 32 characters in the table are programming characters that cannot be shown on the screen.
These include characters like a carriage return character (which shows where a new line should start) and a
horizontal tab character which added some horizontal space. The full list of these 32 programming characters
is given in the table below.
32 SPACE 61 = 90 Z 119 w
33 ! 62 > 91 [ 120 x
34 “ 63 ? 92 \ 121 y
35 # 64 @ 93 ] 122 z
36 $ 65 A 94 ^ 123 {
37 % 66 B 95 _ 124 |
38 & 67 C 96 @ 125 |
39 ‘ 68 D 97 a 126 ~
40 ( 69 E 98 b
41 ) 70 F 99 c
42 * 71 G 100 d
43 + 72 H 101 e
44 , 73 I 102 f
45 - 74 J 103 g
46 . 75 K 104 h
47 / 76 L 105 i
48 0 77 M 106 j
49 1 78 N 107 k
50 2 79 O 108 l
51 3 80 P 109 m
52 4 81 Q 110 n
53 5 82 R 111 o
54 6 83 S 112 p
55 7 84 T 113 q
56 8 85 U 114 r
57 9 86 V 115 s
58 : 87 W 116 t
59 ; 88 X 117 u
60 < 89 Y 118 v
The final 127th character is the DELETE character, which is used when something needs to be removed
or deleted.
Edit edt Used for single line input, but also displays information.
List Box lst Multiple line display. Able to display left aligned columns.
Combo Box cmb Multiple line capturing. Selection of item through drop-down.
Additional Group
BitButton btt Button with icon - used to activate actions.
Win32
Page Control pgc Special page component hosting tab sheets.
System Group
Timer tmr * Count down timer – initializing action as count-down reaches 0.
Samples Group
Spin Edit sed Integer input component with pre-set range to select from.
double variable contains any positive and/or list allows you to store a large number of elements
negative numbers (including decimal numbers) which can be accessed using an index and
which must all be of the same type
E
logic error these errors occur when there is a
event-driven an event-driven program is one that logical error or design problem in your program
largely responds to user events or other similar loop a sequence of an instruction that is continually
input repeated until a certain condition is reached
exponentially more and more rapidly
M
F
mathematical operators the symbols used to tell
factor any number that can be divided into Delphi to add, subtract, multiply or divide two
another number (the multiple) without leaving a numbers
remainder method (Delphi) a method is a function that is
feedback whenever a user interacts with an programmed into an object (such as a label or a
application, they should receive feedback that string) by the creators of Delphi
acknowledges the interaction and informs them mnemonic a tool to help remember facts or a
of what’s happening large amount of information
You can use the QR codes on these pages to link to online content for further
information on these topics.
Introduction
WHAT MOST SCHOOLS DON’T TEACH ........................................................... iv
Chapter 1
WHAT IS BETA TESTING? .................................................................................. 4
Chapter 3
TOP TEN DISASTROUS SOFTWARE BUGS ..................................................... 54
Chapter 4
LEARNING ABOUT ORDER OF OPERATIONS ................................................. 63
Chapter 7
A COMPUTER SCIENCE QUESTION ................................................................. 153
Chapter 9
HOW TO WRITE GOOD USER STORIES .......................................................... 259