Delphi Grade 11 Textbook
Delphi Grade 11 Textbook
1
Introduction to
Delphi
1
Chapter 1: Introduction to Delphi 1
Module
Introduction Introduction
Chapte
r
1
to Delphi
In Grade 10 you were introduced to visual programming and you used the programming
language called Scratch to develop programs. The programming instructions in Scratch are
pretyped and are available for the programmer to select and arrange (drag and drop) in the
required order to complete a specific task.
In this book we will teach you how to plan, design and develop programs in the Delphi
programming language. With programming languages such as Delphi, Java, C# and many
others, the programmer types out instructions. The
formulation of instructions as required gives language. One such feature is the
the programmer more freedom to develop
Delphi refers to a program as an application. In
programs for a wide variety of applications. this book the terms are used interchangeably.
Delphi has many excellent features that
make it a good choice as a programming
fact that Delphi is a RAD (Rapid Application Development) tool, which means that you
can develop an impressive software application in a relatively short period of time. This is
possible because Delphi contains predesigned components that can be used to build the
user interface. Some of the other features of Delphi that will be discussed in more detail
later on are the following:
• Delphi is an event-driven language.
• It supports Object Oriented Programming (OOP).
• Delphi is an excellent programming language to use in order to create applications that
can connect to virtually any database.
• Delphi can be used for applications that run on operating systems using windows such as
Linux, MS Windows or the Macintosh platform.
• Delphi can be used to develop applications for the Web.
One of the most valuable assets of Delphi is the ease of use from a programmer’s point of
view. The programming code itself consists of ordinary English words which closely relate to
the style of an algorithm. Once you have designed an algorithm to solve a problem, it is easy
to convert the solution into Delphi.
Now we are going to look at how to create basic programs in Delphi and how to do very
simple input and output.
2
First acquaintance with Delphi
Get to know the Delphi programming
environment Start Delphi by double-clicking the Delphi icon on your
desktop or on the Start menu.
The screen that opens is referred to as the Delphi IDE (Integrated Development
Environment). It contains all the necessary design tools to develop a Delphi application.
Object
TreeView
Code Editor
where
code or instructions
are typed.
Object
Inspector (OI)
It saves the programmer construct the visual interface of
Properties tab programs. Components from the
time by not having to use the
Events tab Component Palette are placed on
menu every time common the Form.
commands are used. Move the
mouse over the speed bar to see
some of the options.
• Start Delphi.
• Open the application called frmPlayWithDelphi_p (File | Open Project).
• Select the Form (click on it).
• Notice that the name Form1 is now displayed at the top of the Object
Inspector.
• Move the mouse pointer to the Properties tab of the Object Inspector.
• Click on the Caption property and type in new text, e.g. My First Form.
• See how the caption of the Form changes.
• Click on the Color (American spelling for an American program)
property. • Select a colour from the list and see how the colour of the
Form changes. • Change the height and width of the Form. (You can do
this by changing the values of the properties or by dragging the sides of the
Form.)
• See if you can change the font of the Form to Comic Sans and use a 12pt font size.
(See how all components on the Form inherit this property of the Form.) • Click on
the Label.
• Change the Caption property of the Label to Any comment can be typed here.
• Change the Color property.
• Change the Width property.
• Click on the Button.
• Explore the properties of the Button by changing some of the values.
• Click on the Edit.
• Replace the text in the Text property with your name.
• Explore some of the other properties of the Edit by changing some of the values.
• Close the application. (File | Save) then (File | Close All).
4
Notes:
• A Form is the container component on which other components are placed when a
user interface is created.
• The properties of a component describe what the component will look like (its
characteristics), such as the Caption, Width, Height and Color.
• The properties of a component can be viewed by selecting the component and then
by clicking on the Properties tab in the Object Inspector (OI) window. • The properties
are arranged in alphabetical order in the OI.
• The Caption property of a Button and a Label determines what will be displayed on
the component.
• The Text property of an Edit determines what will be displayed in the Edit.
Each tab contains a library of ready-made components that can be used in programs.
Let us have a look at the Delphi files that are created for each program and how to save the
Unit and Project files.
• First create a folder on the computer where you can save your work. You can name the
folder [Delphi Programs Gr 11], or any other suitable name. (Note: The square brackets [ ] do
not form part of the folder name, they just indicate the start and end of the name.)
• Start Delphi or open a new application if Delphi is still open. (File | New | Application)
• Save the Unit file. (Select File | Save As)
• Browse to the folder [Delphi Programs Gr 11] and open it. Create a folder for this program
called [First Program] inside the main folder [Delphi Programs Gr 11].
Chapter 1: Introduction to Delphi 5
Module
Click this icon to create a
new folder.
Delphi files
• You only need to save two files for a new application – the Unit (.pas) and the Project (.dpr) files. The other
files are created and saved automatically when you create and run the application.
• The following three files are the only files you need to copy when you want to transfer your application to
another computer. Delphi will recreate the other files when you run the program again.
The Project file (.dpr) The Form file (.dfm) The Unit file (.pas)
• By default, the Unit files are called Unit1, Unit2, etc. and the Projects are called Project1, Project2, etc. We
add a _u for a Unit file and a _p for a Project when we save these files.
• The names of the project and unit files do not have to be similar to the name of the Form. However, later in
this book, you are going to create more files that will become part of the project. We prefer to add the
prefix frm to the files containing the Form, for example frmFirstProgram_p and frmPlayWithDelphi_p. This
will make it easier to identify the different files that are going to form part of the projects.
Create an interface
Now that you are able to store a Delphi program, we are going to learn to use components
to create an interface for an application.
6
Placing of components
To place a component on a Form, click on the component’s icon on the Component Palette and then
simply click on the Form.
To change the position of components, you can click on them and drag them around the
Form. To resize components, you can click on them and
drag the handles (the black boxes).
To remove a component, simply click on it
and press
<delete> on the keyboard.
You will find the Label and Button components on the
Standard Tab of the Component Palette Label
and you will find the Shape and Bitmap Button
Button on the Additional Tab.
• While the program is running, click on the [Up!] Button. Nothing happens because
the Button contains no instructions to execute!
• Click on the [Close] Bitmap Button to terminate the program.
• Save the program (File | Save All).
• Close the application (File | Close All).
Module
Bitmap Buttons
Bitmap Buttons can be used to make the interface more professional.
Bitmap Buttons are a special type of Button that can have a caption, as well as a bitmap image (picture) on
their face. There are a few different types of Bitmap Buttons. Some Bitmap Buttons perform certain functions
automatically, while the programmer has to add code to others.
The [Close] Bitmap Button is pre-programmed. When you click on it, the program will be terminated because
the code to make this happen is built-in.
This is where the fun starts! We can now add our own programming code to make things
happen!
Do basic processing
Write code for an event
Up until now we have placed components on
the
Form and changed their properties, but we
have
not actually written code to create a working
program.
Nothing can happen in a Delphi application if an
action (or event) has not been triggered. In Scratch you were able to specify events that
indicated when code (or scripts) should execute.
The most obvious actions that will trigger an event that a computer can respond to are
those generated by the user’s interaction with the computer. For example:
• clicking a mouse button
• moving the mouse
• pressing a key on the keyboard.
In the following activity you will learn how to tell a Delphi application what needs to happen
(in other words, you will provide instructions through code) when the user clicks on the
component. This is called an OnClick event. (Later in the chapter we will work with more
events.)
8
• Double-click on the [Up!] Button.
The Code Editor window now appears with a framework or skeleton code of the
instructions that should execute when the [Up!] Button is clicked. (Do not change any
of the given skeleton code. Your program will not run without it – we will explain this
later on.)
• Type the following code between the begin and TObject); begin
the end statements of the skeleton code. shpCircle.Top := 120;
btnUp.Enabled := true;
procedure TfrmFirstProgram.btnUpClick(Sender:
btnDown.Enabled := false;
TObject); begin
shpCircle.Top := 10; lblMessage.Caption := 'Coming down!';
btnUp.Enabled := false; end;
btnDown.Enabled := true; Compile and run the program:
lblMessage.Caption := 'Going up!'; • Click the [Run] icon.
end;
• Now click on the Buttons and see what happens.
• Doubleclick the [Down!] Button.
• Click on (File | Save All) to save the Unit and
• Type the following code between the begin and Project files.
the end statements of the given skeleton code.
procedure
TfrmFirstProgram.btnDownClick(Sender:
correctly, followed by a dot, a list of the properties of
the component appears for you to select from!
Notes:
In Scratch you could drag and drop pre-typed
The Form with the components is in the background.
statements. In Delphi we have to type out
Simply press <F12> to move it to the foreground.
instructions.
Press <F12> again to see the code.
Module • The statements, instructions or code in the event handlers all have the following format:
The value on the right hand side of the assignment sign is stored
in the property on the left hand side.
ComponentName.Property := Value;
and a dot, followed by the between the : and =.
property you want to The value that must be
The name of the component change. assigned.
Assignment sign. No space
The end of a Delphi statement is indicated by a ; (semicolon).
• There are two ways in which to determine the properties that are available for a
component:
- Select the component and look at the properties available in the OI.
- When you type the name of a component in an event handler, a list containing the
properties will appear as soon as you type the dot. You can select the name of a
property from the list by pressing the <enter> key when the name of the property is
highlighted.
• By placing an ‘&’ in front of a word (for example, &Red) in a Button’s caption, a shortcut
key is created (Accelerator (Hot) Keys). The button can then be activated without the use
of the mouse. Press <Alt> and the letter, for example <R>. If the Button is in focus, you
only need to press <R>.
10
When you double-click on a component, such as a Button, Delphi provides a framework
(or skeleton) of the relevant event handler where you have to enter the code (or
instructions). You have to let Delphi create the framework for the event handler because
this establishes the link between the component, the event and the code – you should
not type the framework yourself.
The header of the event handler provides information about the event handler:
procedure TfrmFirstProgram btnDown Click (Sender: TObject);
.
Keyword The event The The event is This tells the
referring to a handler is component’s 'click on the event handler
piece of linked to a name is component'. which
executable code. component btnDown. component
that is part of triggered the
the Form with event.
the name
frmFirstProgram.
As a beginner Delphi programmer, you just need to be able to identify the component and the
event that the event handler has been linked to.
Remember that the Form’s name and the file names do not have to be similar, but we prefer to give
names that indicate which Form is part of which program. In the previous example, we chose the
following names:
Form name frmFirstProgram
Module - The user must be able to make use of accelerator keys to run the program.
- Save the application as frmButtonSize (i.e. the unit file should be saved as
frmButtonSize_u and the project file should be saved as frmButtonSize_p).
12
Data compatibility
In Scratch, data types are handled internally by Scratch. In Delphi, the programmer has to ensure that data
types are handled correctly. When you assign a value to a property of a component, the new value must be a
type of data that the property can accept.
String
Example: The text Going Up! is assigned to the Caption property of the Label with the name
lblMessage: lblMessage.Caption := 'Going up!';
• A string is a collection of characters.
• A string is enclosed in a set of single inverted commas.
Integer
Example: An integer value of 10 is assigned to the Top property of the Shape with the name
shpCircle: shpCircle.Top := 10;
• Integer values are not enclosed by inverted commas.
Boolean
Example: The Boolean value false is assigned to the Enabled property of the Button named
btnUp: btnUp.Enabled := false;
• A Boolean data type can only be true or false.
• The Boolean value true or false is not enclosed in inverted commas.
Hint:
Use the OI to explore the data types of the properties of components.
communicated. Just like human languages,
computer languages (like Delphi or any
other programming language) also have
syntax rules.
Dealing with syntax
errors Syntax is a word which basically includes all the
spelling, grammar and punctuation rules of a
Languages have rules that specify how the language.
language can be written or spoken so that
people can understand what is being
People have the ability to think – so when we make a mistake in communicating and break
the rules of a language, the person we are communicating with can often guess what we
mean. Remember that computers don’t have the ability to think. Computers can’t guess our
meaning if we break the rules of syntax. They just get confused, stop what they are doing
and show us where the mistake is. They cannot go any further until we fix the mistake.
When you compile a program, Delphi takes the code that you have written and translates
it into binary instructions that the CPU will understand. Compilation errors occur when you
have broken one of the rules of the language – such as forgetting a semicolon at the end of
a line. If a compilation error should occur whilst translating in the IDE, Delphi will activate
the Code Editor and position the cursor at the error in the source code. Fortunately, error
messages are displayed to help you correct syntax errors. The message is unfortunately not
always selfexplanatory though.
14
By now you should see that a program will not run until you have fixed all the errors. Some
error messages clearly indicate the problem, while others are more difficult to interpret.
Try to fix these problems by yourself before you call the teacher when you write programs
on your own. This way you will learn to work very accurately and you will also learn how to
interpret error messages yourself.
5. List the two files that you have to save when you save a Delphi program.
6. Write the correct statement to change the properties of the following components as
indicated:
a) Write the code to change the properties of frmForm as follows:
(i) Change the height to 200.
(ii) Change the colour to blue.
(iii) Change the caption to Form Colour.
(iv) Change the size of the font of the Form to 12pt.
b) Write the code to change the properties of btnShow as follows:
(i) Change the height to 30.
(ii) Disable the Button.
(iii) Change the caption of the Button to Show.
(iv) Hide the Button.
7. Complete the following table by indicating which components contain the properties
listed:
Caption Text Font Name Lines Enabled WordWra
p
Button 4 4 4 4 4
Label
Edit
Panel
Memo
CheckBox
Module
8. Use the OI and indicate the data type of the content of the properties of the following
components:
Component Property Data type Example of content
Enabled True
Top Integer
Label Caption
Width
Visible
Panel Hint
TabOrder
Locked
Use a component’s pre-programmed tasks
You already saw that components have certain properties which determine what the
component looks like. These properties can be changed in the OI, as well as through
programming code.
Each component also has specific tasks that it can perform. For example, some components
can hide themselves or they can remove the content they display. The instructions to
perform these tasks are built-in (preprogrammed) code, which is part of the component.
These built-in tasks are called the methods of the component. Activating a method of a
component has the following format:
ComponentName.MethodName ;
• Clear and SetFocus are methods associated with an Edit. SetFocus places the cursor (or
the focus) on the associated component, for example the Edit in this activity. The Clear
method cleans the content of the Edit.
• Both Edits and Labels have Hide and Show methods.
16
Notes:
• Some components do not have a Clear method (e.g. a Label). You have to ‘clear’ a
Label yourself by assigning an empty string to the caption of the Label.
lblMessage.Caption := ʹʹ;
An empty string is represented by two single inverted commas next to one another.
You have to use two keystrokes – do not use double inverted commas.
Produce output
Specific components have specific purposes in a program. For example, a Label is used to
display information, while a Button is usually used to trigger an event. Components such
as Labels and Panels that are used to display information are often referred to as output
components. In general, output components contain the information to be displayed as
strings in their Caption or other string-type properties.
String output
In the following activity you will learn how to use two new output components to display
text values (strings) on the Form.
• To display output on a Label and a Panel you need to place a string into the Caption
property.
• A Memo works differently to a Label and Panel. A Memo contains a list of lines which
is seen as an object itself (the Lines object). The Lines object has an Add method.
When this method is called, the object knows it must add a specific line (or string) to
its display (the task or action it needs to perform). The string to be displayed must be
sent (or passed) to the method. This is done by placing the string in brackets. A value
which is passed to a smaller part of a program is called an argument.
procedure TForm1.btnCalculateClick(Sender:
TObject);
begin
pnlOutput.Caption := IntToStr(6 + 3 * 5);
lblOutput.Caption := FloatToStr(6 * 12 / 7);
end;
Note:
• The calculation (6 + 3 * 5) produces an decimal value
In Delphi the multiplication is an * and real
integer value as a result. The function takes
division is a / (similar to Scratch).
the Integer value and converts it To a String.
• The calculation (6 * 12 / 7) produces a
(floating point value) as a result. The function takes the Floating point value and
converts it To a String.
• The resulting strings are placed in the Caption properties of the output components.
you can call to perform specific tasks. Functions and procedures will be discussed in more
detail in a later chapter in this book.
The following examples show the code to call the ShowMessage procedure and how the
output will be displayed:
Receive input
The ÷ character is
Module Note:
• A user types input into an Edit.
• The program obtains the value from the Text property of the Edit.
• An output string can be created by concatenating substrings using the '+' sign. • The
word 'Hello ' and the space ' ' are substrings the programmer added to the
content of the Edit edtFirstName and the Edit edtSurname to construct the required
output string.
20
No conversion is required since the data types of the values, for example 25 (an integer), are
the same as those of the three properties.
However, if these statements are used, the date
shown on the Calender will always be the same. In this
application we want the user to be able to enter
different
values in the Edits every time the program is executed.
The user input must be shown on the Calender.
Therefore the following code will be more suitable:
The Calender component does not display the month and year in words. You
need to create your own output string (in this case for the Panel component) if
you want the date to be displayed in words.
Note:
• The Day, Month and Year properties of the Calender components are integer data
types.
• The Text property of the Edit component is a string data type.
• The StrToInt function converts a String (the text in the Edit) To an Integer value and
assigns the integer value to the integer property of the Calender for the day, month
and year.
This program can be used to determine on what day of the week you were born or on what
day of the week school will start. This program is available in the Data folder of the book.
pnlOut.Caption := 'This is the day of the week for ' + IntToStr(sedDay.Value) + '/' +
IntToStr(sedMonth.Value) + '/' + IntToStr(sedYear.Value); end;
22
Activity 14: Explore different events
The colour of the Form should change to When the Form is activated.
blue. (Tip: You can determine which
colours are available by clicking on the
drop-down menu in the OI next to the
Color property of any component.)
The Edits must be cleared.
The focus must be set to the first Edit.
Change the colour of the Labels. When the mouse pointer touches a
Label (OnMouseMove event).
A message ‘Use the <tab> key to move to When the user right-clicks on the
the next Edit’ must be displayed. Form (OnContextPopUp event).
The font style of the Button must change When the user double-clicks on the Form.
to bold. (The statement
btnClickMe.Font.Style := [fsBold]; will
change the font style of the Button.)
The colour of an Edit must change to grey. When the user clicks in the Edit
(OnEnter event).
The colour of an Edit must change to white. When the focus leaves an Edit
(OnExit event).
2. Write code to make the following happen and indicate to which one of the event
handlers marked a) to e) the code should be added to:
• Change the colour of lblColour to green when you click on frmInterface. •
Change the width of frmInterface to 40 when you double-click on lblWidth.
• The instruction ShowMessage('Hi clever student!') ; will make the message appear
in a window. This should happen when you touch lblColour.
a) procedure TfrmInterface.lblWidthDblClick(Sender: TObject);
b) procedure TfrmInterface. lblColourKeyDown (Sender: TObject);
c) procedure TfrmInterface.FormClick(Sender: TObject);
d) procedure TfrmInterface.FormDblClick(Sender: TObject);
e) procedure TfrmInterface.lblColourMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
Module
Structure of an object
In OOP languages, objects are predominantly used to create applications. The only objects
you have used and know about so far are components (including the Form). We are now
going to look at some terminology relating to objects.
All objects (both objects used to create applications, as well as objects in real life, such as a
chair, a cellphone, a car, etc.) can be described to another person by mentioning their
characteristics, as well as their function/s. In OOP languages, we refer to the characteristics
of an object (what it looks like and what it contains) as its attributes and we refer to its
actions (what it can do) as its behaviour.
A component as a special type of object
In general A real life object An A
An
• The attributes of a component are described through the component’s properties and events.
• The behaviour of a component is described through its methods.
• Events are considered to be special properties linked to code (event handlers). The event
handlers get executed whenever a particular action occurs (an event is triggered).
24
Definition of an object
Before a house or a car can be built, we need to draw up plans to determine what the house
or car should look like. These plans are only plans and not the physical house or car yet. The
plans only represent what the house or car will look like. Once the plans have been
completed, many houses and cars can be built by following the plans. For a house or car, these
plans are called the blueprints. For a programming object, the plan for an object is called the
class. Once an object has been created, we say the object is an instantiation of the class.
The class definitions of the components we use
are stored in libraries of code called Units. The
names of these classes all start with a capital ‘T’.
(The T indicates that the class represents a Type
and is an old Borland convention.) When we place
a component on the Form, we can see to create applications that respond to the
which class the component belongs to in actions that
the OI, as seen alongside: btnCalculate is an instance of the class TButton.
the user takes. For example, when the user clicks on a Button, a calculation needs to be done
based on the data entered in Edits.
Previously, we said a Form is the container object for many other objects. When we place
components on a Form and write event handlers for the events of the components, we are
actually creating a new object. However, an object cannot exist without having a class
definition, so where is the class definition for the Form? While we are developing a program,
Delphi actually creates the class definition for us. Delphi does this by basing the Form
definition on a predefined form class (Tform) and then adding more information as we
develop the program.
All you need to be able to do at this stage is to identify the attributes and behaviour of the
class definitions of the Forms you create.
When you first create a new Form, the class definition is Once you rename the Form, the name of the
empty. It can be found at the top of the Unit file of the class will change automatically.
Form:
type type
TForm1 = class(TForm) TfrmFirstProgram = class(TForm)
private private
{ Private declarations } { Private declarations }
public public
{ Public declarations } { Public declarations }
end; end;
var var
Form1: TForm1; frmFirstProgram: TfrmFirstProgram;
Module type
Once you add components and event handlers to the Form, Delphi will add references to
these components and event handlers to the class definition.
TfrmGetData = class(TForm)
edtName: TEdit;
edtSurname: TEdit;
edtAge: TEdit;
lblName: TLabel; lblSurname: TLabel; the new Form's class. The behaviour
lblAge: TLabel; defines what the Form will be able to do.
btnReset: TBitBtn; btnEnglish:
TButton; btnAfrikaans: TButton;
btnSepedi: TButton;
{ Private declarations } public
Attributes (all the components) of the new
Form's class. These attributes define what { Public declarations } end;
the Form looks like.
var
frmGetData: TfrmGetData;
You will learn what can be added in the
Behaviour (methods = private and public section of the class
the event handlers) of definition later.
procedure btnResetClick(Sender:
TObject); procedure
btnSepediClick(Sender: TObject); The declaration of the variable
procedure btnEnglishClick(Sender: frmGetData which belongs to the class
TObject); procedure TfrmGetData.
btnAfrikaansClick(Sender: TObject);
private
If you decide that you don’t need an event handler any more, you just need
to delete all the code between the begin and end statements of the event
handler and save the program. Delphi will remove the declaration of the
event handler from the class definition.
26
unit frmBirth_u; interface The name of the unit that was decided on when you
uses saved the Unit file.
• The Delphi programming language is event-driven and is regarded as a RAD tool because of the
predesigned objects that the programmer can use, such as the Form and all the drag and drop
components.
• Each Delphi program consists of
- an interface (the Form and components)
- a unit (containing code written by the programmer).
• A Delphi program is developed in the Delphi IDE which consists of several windows (e.g. the
Object Inspector, Object TreeView, the Form and the code editor), as well as development tools
(e.g. the Component Palette).
• The Form is an object with properties that can be changed in the OI. These are referred to as
static changes.
• When the properties of an object change while the program is running (e.g. the colour of the
Form changes when the user clicks on a button or the Form), it is referred to as a dynamic
change. Dynamic changes are normally done by the execution of programming code.
• A Delphi program consists of several files. The Project, Form and Unit files are the most important
files.
• Each component has its own set of properties (e.g. Name, Caption, Left, Top, Color) and events
(e.g. OnClick, OnMove, etc.).
• The actions that must take place when an event occurs, e.g. when the mouse is clicked, must be
typed out as programming instructions inside the event handler of the specific event (e.g. inside
the event handler for the OnClick event of the Button).
• An event handler consists of a framework provided by Delphi and code is added to the event
handler.
• Code is added to the event handler in the Code Editor.
• The code that you enter are linked to an event of a component.
• All programming languages have rules that have to be followed when you enter programming
code. Syntax errors occur when these rules are violated.
• Once all the syntax errors have been corrected, the programming code is translated into machine
code by means of a piece of software called a compiler. The machine code is then executed.
28
The diagram shows the relationship between the different parts of an event-driven program. •
Clicks a Button
change
• Error message
e.g. printer not on.
Object Other
is an instance of a Operating system • Software
• Closes an
defines an application drivers
User
Class
• Selects an item
• Date or time
• Application Events
is a special type of software
Component
Actions
described through
has
perform
Attributes and
triggers
Behaviour
linked to
described through
Properties
applications
handlers implemented
through
Behaviour implemented
Event through
Procedures
Behaviour
Procedures or
functions
Object A structure that has been previously defined and that is used
when developing a program. Each type of object has specific
features and can perform specific tasks.
Object Inspector A window on the IDE which displays the properties and events
of a component.
Programming language The tool or language programmers use to write computer programs.
Properties of a component Properties describe what the component will look like (its
characteristics), such as the Caption, Width, Height and
Color.
Syntax error An error that occurs when the rules of the programming language
are not followed.
30
Use keystrokes or menu options
For many of the menu options and/or icons,
there
is more than one way to activate the option. For
example, to run a program you can click on the Run icon, the run menu option, or push F9.
You can see the options that are available when you click on the menu option or icon.
Indication of error
If you do not see an error indicated by Delphi (indicated by red lines) in the line of code, the
error could be in the previous line.
Select and change properties of more than one component at the same time
We often need to set the properties of various
components (such as the three Labels) to the
same
value. For example:
• We want all three Labels to be aligned exactly
below one another – i.e. the Left property of
all
three must, for example, be set to 50.
• The font of all three Labels must, for example, be set to Arial 12pt, bold.
We can simultaneously select all three Labels by holding down <Shift> when we select the
components. If we then change the property in the OI, that property is changed for all the
selected components.
Note: The components you select do not have to be the same, but the OI will reduce its list
of properties so that it only shows the properties that all the selected components have in
common.
Click on the name of the component The component will now be placed on
that should be moved onto the the Panel and this will be reflected in
Panel in the Object TreeView. Hold the Object TreeView by the name of
the mouse button in and drag the the component that appears indented
component’s name to the name of below the name of the Panel.
the Panel.
Module
Improve the user-friendliness of an interface
User-friendliness is designing your program and its interface so that it is easy to use.
• Use Labels to tell the users what is expected of them.
• The instructions need to be clear.
• The layout of components on the Form should be easy to follow.
Improve the readability of programming code
Programming code has to be readable, easy to analyse and its logic must be easy to follow.
To accomplish this, apply the following guidelines when typing programming code:
• Use descriptive names for components and variables (which we will discuss later).
• Make use of indentation of the instructions to improve readability.
• Use blank lines to group sets of related instructions.
• Use comments to briefly explain the purpose of the code.
• Type one basic instruction per line.
Left 0
Top 0
Height 100
Width 75
Caption &Yellow
Left 0
Note: to change the colour of a shape you need to
change the brush property of the shape, e.g.
shpRed.brush.color := clRed;
32
Shape1: Name shpRed
Shape stCircle
Left 100
Top 20
Height 65
Width 65
Shape stCircle
Left 100
Top 120
Height 65
Width 65
Shape stCircle
Left 100
Top 220
Height 65
Width 65
For each of the Buttons, write an event handler for the OnClick event.
• For the [Red] Button, the event handler must change the colour of shpRed to red; for
the [Yellow] Button, the event handler must change the colour of shpYellow to yellow;
and for the [Green] Button, the event handler must change the colour of shpGreen to
green. (Remember if one light switches on, the other two must switch off.)
• Save the unit file and the project file as frmTraffic_u and frmTraffic_p respectively.
• Run and test the program.
with btnRed do
begin
Caption := ‘&Red’;
Left := 0;
Top := 0;
Height := 100;
Width := 75;
end;
• Create a new application.
• Place three Buttons and three Shapes on the Form.
• Add code to set up the components to represent a traffic light.
• When a light is switched on, don’t ‘switch off’ the other two lights. Let them change to
a lighter shade. You can run the .exe file provided for this program.
• Add an event handler for the OnMouseMove event for pnlGreen. When the user
moves the mouse over the Green panel, the colour of pnlSlave must change to
green.
• Do the same for pnlRed.
Tip
• Save the unit file as frmMouseMove_u
Do not give pnlSlave a specific colour.
and the project file as Use the statement:
frmMouseMove_p. pnlSlave.Color := pnlGreen.Color;
• Run the program. etc.
OnMouseMove event for the Form. When the mouse moves over the Form, the
colour of pnlSlave must change to the colour of the Form.
See if you can answer the following questions:
- How many OnMouseMove events take place when you move the mouse from left
to right over the Form between A and B?
- Can you find the ‘hotspot’ of the mouse arrow?
34
Basic programs in
Delphi
2
Chapter 2
35
STUDY OPPORTUNITIESChapter 3: Custom subroutines
Chapter 2: Basic programs in Delphi 35
Basic
Module
In Chapter 1 you learned the structure and layout
of the Delphi IDE and you used
programs in r
2
Chapte
Delphi
Introduction
components to create interfaces for a few Delphi applications. You learned that it is really
important to assign values of the correct data types to the properties of components.
You created simple programs using the properties of components to do calculations. You
had to convert string data type input into integers before any calculations could be done
and the results had to be converted into string data to be displayed. In this chapter you
will learn how to use variables in Delphi to receive input from the input components, do
calculations and display the results using output components. You will also learn different
techniques on how to plan your programs properly using IPO (Input, Processing, Output)
tables as well as TOE (Task, Object, Event) charts.
We will start with a simple problem for which you will write a Delphi program. We
will use this program to explain how each of the above steps is performed when
developing a Delphi program. This is the scenario:
The Grade 11 learners are selling raffle tickets to raise money for the Matric dance. A
ticket costs R5. You should be able to enter the name of the learner, as well as the
number of tickets that the learner wants to buy. The program must calculate the
amount to be paid, and display it with an appropriate message, e.g. Sheldon, you need
to pay R50.
STUDY OPPORTUNITIES
36 Chapter 2: Basic programs in Delphi
To solve this type of problem, we need to develop an algorithm to provide a step-by
step solution to the problem. Pseudo code for this program can look like this:
Pseudo code
A useful way to plan the solution to a program and decide on suitable components is
to create an IPO table. An IPO table shows the Input, Processing and Output sections
of the program, and can be expanded to indicate which input and output components
are recommended for use when you design the actual Delphi program.
The following IPO table represents an algorithm to solve the given problem and
suggests input and output components:
INPUT PROCESSING OUTPUT
INPUT OUTPUT
COMPONENT(S) COMPONENT(S)
edtName pnlOutput
edtNumber
From the IPO table we can design our Delphi program starting with the design of the
interface. Study the following possible interface of a Delphi program that solves the
problem in our example:
The next step is to write the code to do the processing and solve the problem.
The table below shows the code for the Scratch program and the Delphi solution to
the problem. Identify the similarities and differences between the Scratch and the
Delphi versions of the code.
Chapter 2: Basic programs in Delphi 37
STUDY OPPORTUNITIES
Module
Scratch program Delphi program
procedure TfrmRaffle.btnCalcClick(Sender:
TObject); var
sName : string;
iNumber : integer;
iAmount : integer;
begin
//Input: obtain values from the user via
components sName := edtName.Text;
iNumber := StrToInt(edtNumber.Text);
//Processing
iAmount := iNumber * 5;
//Output
pnlOutput.Caption:=sName + ', you need to pay R'
+ IntToStr(iAmount);
end;
Notes:
• In the above Delphi program we had to declare variables to store the name,
number of tickets sold as well as the amount payable, and indicate the data
type of each variable.
• The Delphi program’s interface provides the opportunity to enter the input
values before the OnClick event takes place. However, in the pseudo code we
still use the words Ask and Get because pseudo code is independent of the
programming language.
• We use the assignment symbol ':=' to assign a value or expression to a variable.
Variable := Value or Result of Expression
or String of text
Delphi variables
Declaring variables
When a variable is declared:
• It should have a name describing its content, e.g. sName, iMark, rPrice,etc. • The
data type of the variable has to be specified, i.e. you need to tell the computer what
type of data will be kept in that variable. The data you plan to save in the variable will
determine its data type. It could be a person’s name (a string), your Information
Technology mark (an integer), the price of an item you want to buy (a real value), etc.
We declare a variable by using the keyword var followed by the variable name, a colon
(:) and the type of the value that will be stored in the RAM allocated to the variable.
var
VariableName : <datatype>;
We can also declare a number of variables of the same type in the same line:
var
VariableName1, VariableName2, VariableName3 : <datatype>;
Variables can be declared in the event handler before the begin-statement. This
corresponds to the variables that we declared For this Sprite only in Scratch. Only the
code inside the event handler where the variables have been declared can refer to
these variables. That means that the scope of these variables (the region where the
variable are accessible) is limited to the event handler.
Chapter 2: Basic programs in Delphi 39
STUDY OPPORTUNITIES
Variable names
When we decide on names for variables, we have to use meaningful words to make our
programs user-friendly and to improve readability. There are, however, some rules that
we must follow when we construct the name of a variable.
Although it is not an official rule, we usually indicate the data type of a variable by the
first letter of the name, because we always have to keep the data type of a variable in
mind when we program. For example, iCount will keep an integer value, and
rAmountOfSales will keep a real value.
Study the following variable names. Indicate whether the name is correct or not. If
the variable name is incorrect, explain why it is incorrect.
a) K1 e) _Discount
b) 1Team f) Exercise1.1
c) Mark_3 g) YesOrNo?
d) Price of Fuel h) Begin
Use the information on primitive data types in Delphi to do this activity. You can
find this information in Appendix A.
Choose an appropriate variable name and data type for each of the following
descriptions of data, and give a reason why you have chosen the specific data
type:
a) The number of oranges in a bag.
b) The length (in hours) of a video.
c) The name of a participant in a singing competition.
d) The average of three marks obtained in the competition.
e) The answer to the question: “Do you like fruit?”
f) The millilitres of milk needed in a pancake recipe.
g) The title of your favourite song.
h) The price of fuel per litre.
i) Whether a team has won a competition or not.
j) A cell phone number.
Calculations
Some of the major differences between Scratch and Delphi we have encountered up
to now are the following:
• All instructions (code) must be typed out in Delphi.
• The data types of variables must be indicated when the variables are declared.
Delphi has a larger variety of numeric operators and mathematical and string
functions than Scratch. In this section we will explore some of these Delphi operators
and apply them in operations.
Numerical operators and data compatibility
Let us explore some of the rules that apply when we work with numerical operators.
In the explanation of these rules we will use the following variables:
Var
iNumA, iNumB, iNumC, iAns : integer;
rValueA, rAns : real;
Chapter 2: Basic programs in Delphi 41
STUDY OPPORTUNITIES
Module
• Numerical operations on integer variables will deliver an integer result. • If
one variable in an operation is of type real, it will deliver a result of data type
real, e.g. rValueA + 10 * 5 – 6 will deliver a result with data type real. • An
integer result can be assigned to real variables, but not vice versa. This is
because a real variable space is constructed differently from the space
constructed to keep integer values. The following assignment statement is
valid:
• The '/' operator always results in an answer of data type real, even if both
values are integers.
8.2 / 3 2.7333
Expression Result
6/2 3.0
Remember: Division by zero will cause
9/2 4.5 a program to stop executing.
• The MOD and DIV operators do integer division. Both the MOD and DIV
operators can only be used with integer variables and the result is always of
an integer data type.
The result of the MOD operation is The result of the DIV operation is
the remainder of a division the integer part of a division
operation. Examples: operation Examples:
1. State whether the following assignment statements are correct. Rewrite those which
are incorrect:
Var
iNum, iAns : integer;
rNum, rAns : real;
cChar : char ;
sLine : string[20];
// Note: sLine has a fixed size and can only keep a maximum of 20 characters
a) iNum := iNum / 2; h) iAns := iAns * 20 / 5;
g) rNum := btnLength.Top;
2. Study the following Delphi program segment:
var • We can use the inc procedure to increase the value
of an integer variable, e.g:
sName : string[20];
cLett : char; - inc(iNumA,3); is the same as iNumA := iNumA + 3;
begin - inc(iNumA); is the same as iNumA := iNumA + 1;
sName := cLett; {1} • We can use the dec procedure to decrease the value
of an integer variable, e.g:
cLett := sName; {2}
end; - dec(iNumA,3); is the same as iNumA := iNumA - 3;
- dec(iNumA); is the same as iNumA := iNumA – 1
Explain why the following error message is
displayed when compiling statement 2 but not
when compiling statement 1.
Incompatible types: ʹCharʹ and ʹShortStringʹ
Order of precedence
In Scratch the order in which different operations are executed within an operation is
determined by the way the programmer rAvg := (iTest1 + iTest2 + iTest3) /
stacks the operator blocks in an operation
3 ; rVAT := 14/100 * rPrice ;
instruction. In Delphi, expressions are
created by typing variable names, rCelcius := (rFahrenheit -31) * 5 /
operators and brackets in a specific
9 ; iEachChild := iNumSweets DIV
required order, for example:
3 ; iNumRemain := iNumSweets
MOD 3 ;
STUDY OPPORTUNITIES
Chapter 2: Basic programs in Delphi 43
Module In Delphi expressions, the same order of precedence than in mathematics is used. This
means that, just like in maths, some parts of the expression are calculated before other
parts, e.g. the parts in brackets are calculated before addition and subtraction are done:
Priority Operation
First Brackets
Third +-
The following table shows a comparison between calculations coded in Scratch and
Delphi.
rAns := iB + iA / 2;
1. In the following expressions, what would the result and the data type of the
result be?
a) 5.0 * 2 i) 3 + 4 * 2
b) 30/2*3 j) 12.5 – 6/3
c) 30/(2*3) k) 30 DIV 8 * 2
d) 2*3 + 30*20 l) (2 MOD 5 + 3) * 10
e) 2-30+3*20 DIV 3 m) 20/5 – 18/3
f) 2-30+3*(20 DIV 3) n) 20.0 / 5 * 2
g) 2-(30+3*(20 DIV 3)) h) o) 20 DIV (10 – 20 DIV 3)
30 MOD 7 p) 20+2*3+(2+30)*2+20*20
2. Write equations in pseudo code for the following tasks. Assume all the variables
have numeric values. Assign the result to a variable x in all the instances. Some
of the statements may be interpreted in more than one way. If so, have a class
discussion on the ambiguity and rewrite the task so it will be unambiguous. a)
Increase the value of A by twice the value of B.
b) Decrease the value of A by thirty five percent.
c) Calculate the square root of B squared increased by A squared.
d) Three times the result of eight times a number increased by two.
e) The difference between two times A and eight.
f) Decrease the product of A and B by the quotient of C and D.
g) Divide A by B and then increase the answer by six percent.
h) Decrease the value of the product of A and B by fifteen percent of the sum
of A and B.
STUDY OPPORTUNITIES
44 Chapter 2: Basic programs in Delphi
3. A Delphi program has been written to do specific mathematical calculations.
Study the statements that form part of the program and answer questions a, b
and c for each statement. (Assume the variables have been declared with data
types according to the naming convention used, e.g. it has been declared that
iValue is an integer data type.)
a) Will the statement(s) compile without a syntax error?
b) Assume the syntax errors (if any) have been corrected. Will the program
perform the calculation without displaying an error message? (No runtime
error occurs.)
c) If no runtime error occurred, will the correct result be displayed? (No logical
error has been made.)
Purpose of statement Delphi code
4. Complete the following program code so the variable iOnes will contain the digit
indicating the ones in a value, iTens will contain the digit indicating the tens in a
value, and the variable iHundreds will contain the digit indicating the hundreds
in a value, e.g. if the variable iValue contains the value 584, iOnes must contain
the digit 4, iTens must contain the digit 8 and iHundreds the digit 5 once the
code has been executed. You may only use the operators DIV and MOD.
iValue := sedValue.Value ;
iOnes := iValue MOD 10 ;
5. Write a program to enter the number of minutes it took you to get from home
to school today in a suitable input component. Display the number of minutes
as the number of full hours and the number of remaining minutes e.g. 65
minutes is 1 hour and 5 minutes.
STUDY OPPORTUNITIES
Chapter 2: Basic programs in Delphi 45
1. Run the program and write down the exact value as displayed. Try to make
generalised comments about FloatToStrF, that can be discussed afterwards in
class. Pay attention to the following:
• Change the format part of the instruction to all possible formats (ffCurrency,
ffNumber etc.) and keep record of all changes and outputs in the table.
• Change the Total number of digits and Number of decimal digits values to
various combinations of small and large numbers.
• Change rValue to negative values and extreme values.
1. Write a Delphi program for the following problem, using the IPO table provided: A
builder wants to calculate the perimeter and surface area of the floor of a room.
INPUT (variables) PROCESSING OUTPUT
edtLength lblPerimeter
edtWidth lblArea
Draw up IPO tables for each of the following problems, decide on input and
output components and then write a Delphi program for each problem:
2. You need to calculate the total price of a number of tickets for a concert. A ticket
for an adult costs R150 and a ticket for a child costs R80. The user needs to enter
the number of tickets for adults and the number of tickets for children. Try and
improve the program by asking the user to enter the price of a ticket for an adult
and a ticket for a child as input rather than using fixed values.
3. A trip to town in a taxi costs R8.50 per person. Enter the name of the taxi driver
and the number of passengers that used this service on a specific day. Calculate the
income of the taxi driver for that day. Display the name of the taxi driver, the
number of passengers, the total income for the day and the possible monthly
income based on the number of passengers for that day, if the taxi operates 20
days per month. Try and improve the program by asking the user to enter the price
of a trip and the number of times the taxi driver will operate per month.
STUDY OPPORTUNITIES
Module 6. Masson’s Bricks wants an application that clients can use to calculate the total
weight of the bricks they bought. This application can be used to ensure they do
not exceed the carrying capacity of their vehicles. The client will need to enter the
weight for one brick that was bought. To allow for a safety margin the program
must add an additional 5% to the total weight of the load.
7. Your local pet shop needs a calculator to determine the volume of rectangular
aquariums. They need to know the volume because the amount of medication
and food for fish are usually specified per volume. The user needs to input the
length, width and height of the aquarium. Since most medications they use for
fish are imported the application must display the volume in litres, UK gallons and
US gallons.
1 litre = 0.22 UK gallons = 0.26 US gallons
This single line of Delphi code, generates the following dialog box:
1. Write a program to ask the name of a person when the Button [Click here to Register]
is clicked and display the message Registered as Name Surname on a Panel below.
Constants
Sometimes a value that should be used in a calculation or operation is already known
when you create a program. For example, the fuel price, VAT, the interest rate on an
investment, the name
of a school, etc. This data can be STUDY OPPORTUNITIES
‘hard coded’ in statements in the
program. However, it is a better
programming practice to store
these values as constants which
means these values cannot be Constants can be declared
changed while the program is either in the interface or in the
implementation section of the Unit
running.
file. If the constants are declared in
Note that an equals sign, =, is the implementation section, all
used when declaring a constant. methods in the unit file itself have
A constant is declared as follows: access to the constants. If they are
Const declared in the interface section,
VATRate = 0.14; other files in the project also have
MinimumBalance = 100; access to them. Since we will be are
Const
ConstantName = <value>; working with programs consisting of
Examples: only one Form or Unit we will
declare constants in the
var
implementation section of our
frmBanking: TfrmBanking;
programs.
implementation
{$R *.dfm}
Chapter 2: Basic programs in Delphi 49
ProgramLanguage = 'Delphi';
Module The value of a constant remains the same during the execution of the program. This
means that constants can be used in statements but their contents cannot be changed
while the program is running. They can be seen as read-only variables.
The following are advantages of using constants:
• Constants are declared with descriptive names.
Creating a constant called VATRate with a value of 0.14 is more explanatory than
simply using the value 0.14 in your code. For example:
rTotalPrice := rPrice + (rPrice * VATRate);
is more explanatory than
rTotalPrice := rPrice + (rPrice * 0.14);
• Constants make it easier to change values in your program.
To change the VAT rate in your program, all you need to do is change the value of
VATRate in the Const declaration. Otherwise you have to change the VAT rate in all
cases where you have used the value in calculations in the program.
1. The cost of jeans at the PickAJean shop includes VAT of 14%. All jeans are sold at
a discount price of 10%. Write a program where the price of a jean can be
entered, and the program should display the name of the shop, the original price
of the jean, the amount of discount received, the amount to be paid and the
amount of VAT included in the amount
to be paid. The name of the shop, the width.
VAT and the discount percentage must
The interfaces for activities 1 and 2 are
be declared as constants.
available with the data for the book. Open
the programs and complete the code in the
2. A person lays floor tiles at a tariff of
relevant event handler(s).
R30.45 per m2. Calculate the total cost
to tile a room of a certain length and
The person wants a deposit of 10% of the cost prior to commencing with the
work, and the balance on completion of the work. A handling fee of R9.25 is
added to each box of tiles that the person needs to work with. A box of tiles
covers 1.25 m2 floor area. Calculate the least number of boxes required for the
tiling, the deposit, as well as the amount that has to be paid on completion of
the work. The 10% deposit fee only applies to the cost of the tiles per area, and
not the handling fee. Use constants where possible.
Duration of a variable
The duration of a variable refers to its lifetime – how long or when the variable exists
while the program is running.
Variables declared in an event handler (or method) are created in the computer’s
memory when the event handler starts being executed. They are destroyed when the
event handler is done being executed. The lifetime of these variables are restricted to
the ‘lifetime’ of the event handler. This is referred to as variables with local duration.
In many applications some of the variables have to exist the entire time while the
STUDY OPPORTUNITIES
Each DVD should have a variable keeping track of the total number of votes casted for
that DVD. Each of these variables will be updated by a separate event handler. These
variables have to exist for the duration of the program and NOT only for the duration
of the event handler (when the learner clicks on the image).
Code for the event handler of the first image:
procedure TfrmDVD.imgDVD1Click(Sender: TObject);
begin
iVotesDVD1 := iVotesDVD1 + 1;
pnlVotes1.Caption := IntToStr( iVotesDVD1);
end;
The variable iVotesDVD1 will be changed many times while the program is running
because it must keep track of the accumulation of votes. If the variable is declared in
the event handler it will have local duration, and it’s contents will be lost every time
the event handler is done being executed.
The solution is to make the variables keeping track of the votes for each DVD part of
the Form, because the Form has static duration. The Form and all its attributes exist
for the duration of the program and variables ‘on the Form’ will not be destroyed
while the program is running. Therefore these variables have to be declared in the
private declaration section of the Form’s class.
Chapter 2: Basic programs in Delphi 51
STUDY OPPORTUNITIES
Module
Activity 10: Use variables with static duration
1. Write a program that will allow learners to vote for the SRC leader at the school.
Put the names (or photographs) of three possible candidates on the interface
and construct the code to show how the scores accumulate when the learners
cast their votes.
In Scratch all variables (those declared For this Sprite only as well as those declared For
all sprites) had static duration. When a Sprite made a change to a variable, that value was
retained, even if the program was closed and re-executed later again.
Scope of a variable
A variable’s scope refers to the part of the program where the variable can be
accessed (where it can be used and where its content can be changed) – we also
refer to the scope as the ‘visibility’ of the variable.
In Scratch you created variables For this sprite only. Those variables could only
be accessed (changed and displayed) by the specific sprite. This corresponds to
variables declared in an event handler in Delphi. These
variables have method scope because variable. The following example explains
only the code in the event handler this concept:
(which is a method) can access them. Variables declared in an event handler have
However, in some applications it is local duration and method scope.
necessary for more than one event
handler to have access to the same
The Outreach Society of a school is raising funds to buy clothes and toys for the
children in an AIDS Home. They have asked the learners to make a contribution of
either R10, R20 or R50 towards the project. The following program is used to keep
track of the amount raised. A variable iTotal is used to keep track of the amount
raised. When the user clicks on the Button [R10], iTotal must be increased by 10.
When the user clicks on the Button [R20], the variable iTotal must be increased by
20 etc.
STUDY OPPORTUNITIES
type
TfrmOutreach = class(TForm)
...
private Declaration of the variable
iTotal : integer; iTotal as an attribute of the
public Form frmOutreach.
{ Public declarations }
end;
Event handler for OnClick nt handler for OnClick Event handler for OnClick
event of event of event of
btnR10 btnR20 btnR50
STUDY OPPORTUNITIES
Module The table that follows explains and compares some of the different scopes of variables
and constants in Scratch and Delphi.
Scratch Delphi
All the sprites on the Stage are All the components ‘on’ the Form can see the
able to see all the variables on variables ‘on’ (or which are part of) the Form.
the Stage. Therefore the scripts Therefore the event handlers of the components
of the sprites can use and make can use and make changes to the variables on the
changes to the variables on the Form.
Stage.
File scope
• Constants and variables which are declared in the
implementation section of a Unit can be used by
all the methods in the Unit.
• You have used constants with file scope in activity
9. • The use of variables with file scope will be
explained in more detail in Chapter 6.
Let us now look at a more extensive program - the FastFoods program (written in
Scratch and provided as data with this book), and write a similar program in Delphi.
In this application we will again make use of variables with class scope and static
duration.
The program provides three items a user can choose from. When the user clicks on the
picture of the items he/she wants to order, the program must ask how many of this
STUDY OPPORTUNITIES
unit frmFastFood_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms, Dialogs, ExtCtrls, StdCtrls;
type
TfrmFastFoods = class(TForm)
imgHamburger: TImage;
imgPizza: TImage;
imgCooldrink: TImage;
imgCalculator: TImage;
memOutput: TMemo;
lblInfo: TLabel;
STUDY OPPORTUNITIES
TObject); begin
memOutput.Lines.Add('Number of items: ' +
Module implementation IntToStr(iCount)); memOutput.Lines.Add(‘Total
{$R *.dfm} amount due: '+
const FloatToStrF(rTotalDue, ffCurrency, 8, 2)); end;
HAMBURGER = 35.60 ;
PIZZA = 22.40 ; procedure TfrmFastFoods.FormShow(Sender:
COOLDRINK = 12.30 ; TObject); begin
lblInfo.Caption := 'Click on the item ' + #9 +
procedure
TfrmFastFoods.imgHamburgerClick(Sender:
TObject); var
iNumItems : integer ;
Constants with file scope. They are declared in the
begin implementation section, and are accessible to all the
iNumItems := StrToInt(InputBox('Hamburgers', methods in the Unit file.
'How many do you want to buy?',''));
iCount := iCount + iNumItems ;
rTotalDue := rTotalDue + iNumItems *
HAMBURGER ; end;
Variable with method scope. It is accessible only to the
procedure event handler TfrmFastFoods.imgHamburgerClick.
TfrmFastFoods.imgCalculatorClick(Sender:
1. Write the FastFoods program explained in the previous paragraph. You need to
complete the code for the following event handlers:
procedure imgPizzaClick(Sender: TObject);
procedure imgCooldrinkClick(Sender: TObject);
Add a Bitmap Button [Next Customer] that will clear all the values to allow the
next customer to place an order.
5. Write a program to test the knowledge of the user on variable names. Ask three
questions and supply in each case three possible answers including one correct
answer. When the user clicks on the correct answer the score of the user will
be incremented by 2 (each correct answer is worth 2 marks). When the user
clicks on the [Done] Button the final score must be displayed. Note: Open the
incomplete program for this exercise from the
data supplied with the book and user to do the test again.
complete the code.
The interfaces for activities 2 - 5 are
Improve the program by changing the available with the data for the book.
colour of the correct answer to green Open the programs and complete the
when selected and the incorrect code in the relevant event handler(s).
answers to red when selected. Also
include a [Reset] Button to allow the
Identify Task, Object and Event
Previously we showed you how to plan a program using an IPO chart. Another way
to plan a program (especially when the program has many events), is to use a TOE
(Task Object Event) chart. To construct a TOE chart you identify tasks, decide which
component(s) you are going to use to implement the task and decide on which
event(s) each task will be performed. Consider the following application:
A R10 shop (where all items cost R 10.00) uses a program to calculate the cost of the
items bought, and the change that a customer should receive. To create a TOE chart
for this application we first need to identify the tasks at hand and decide on the
objects (components) to be used.
Chapter 2: Basic programs in Delphi 57
STUDY OPPORTUNITIES
Module For our R10 shop application, the tasks at hand and the related objects
(components) would be the following:
• The first task would be to obtain the number of items bought by the customer,
using a SpinEdit.
• The second task would be to calculate the cost of all the items. We assign this
task to a Button, btnBuy.
• The third task would be to display the cost of the items, using a Memo
component. This task also relates to btnBuy. (Note that two objects are used for
this task.)
• The fourth task is to obtain the amount of money that the customer uses to pay,
using an Edit component. We also assign this task to a Button, btnShowChange,
and the amount will be entered using an Edit component.
• The fifth task is to calculate the change. This task still relates to button
btnShowChange.
• Task number six is to display the amount of change, using a Memo. This task also
relates to Button btnShowChange.
Up to this stage, our TOE chart will appear as follows:
Task Object (Component) Event
Obtain the number of items sedNumItems
bought Calculate the cost of all btnBuy
the items Display the cost btnBuy, memCashSlip
Obtain the amount the customer btnShowChange, edtPaid
paid Calculate the change btnShowChange
Display the amount of change btnShowChange, memCashSlip
Next we have to decide what event should be executed to perform each task.
Sometimes no event is associated with an object (component) or task, for example,
when a user enters a value in an Edit, the value is displayed in the Edit anyway and
therefore an event is not required to take place.
In our example, we are going to use the following events:
• The number of items bought will be read when the user exits sedNumItems (in
this particular program, we have decided we want to do it this way and not when
the user clicks on a Button).
• When the user clicks on btnBuy, the cost of all items must be calculated and
displayed.
• When the user clicks on btnShowChange the amount paid has to be obtained
and the change must be calculated and displayed.
Note: There are no fixed rules when deciding on which components to use and to
which events the tasks should be linked. There are some basic guidelines but how
the events should flow while a program is running has to be planned around the
preferences and abilities of the users.
The programmer should try and find the most natural way the user would like the
events to flow when they use the program.
STUDY OPPORTUNITIES
use these tools, but you do have to use them whenever you design your programs.
In the solution for the R10 shop program, an event handler will be written for each
event in the TOE chart. The tasks should be translated into pseudo code as you did
previously.
type
TfrmRegister = class(TForm)
....
private
rAmount : real ;
iNumItems : integer ;
public
{ Public declarations }
end;
var
frmRegister: TfrmRegister;
implementation
{$R *.dfm}
procedure TfrmRegister.btnBuyClick(Sender: TObject);
begin
rAmount := iNumItems * 10 ;
memCashSlip.Lines.Add('Total : ' + FloatToStrF(rAmount,ffCurrency, 8, 2)) ;
end;
Chapter 2: Basic programs in Delphi 59
STUDY OPPORTUNITIES
2. Write a Delphi program to implement the TOE chart created in activity 12.1.
3. Create a TOE chart as part of the planning process before writing a program for
the registration of students at a community college. Enter the name and the
average Grade 12 mark. The class fee is R25 000 per year for all the students.
Add the following buttons:
• [Distinction] Button to decrease the class fee by 10% when the user clicks
on this button
• [Residence] Button to add R50 000 to the fee for staying in the residence
• [Bursary] Button to reduce the total fee by 80% because a bursary pays 80%
of the total fee of students at the college.
The student click on the buttons described above only if applicable.
The initial fee of R25 000 must be displayed on a Panel when the program
starts and this fee must be updated when the user clicks on any of the buttons
that are applicable.
STUDY OPPORTUNITIES
4. Write a Delphi program to implement the TOE chart created in activity 12.3.
Study support
Overview of variables
File scope
Class scope
Method scope
Size in bytes
Data Type
depending on where it was declared in • Different variables take up a different
the program. Value number of bytes in
• RAM address
STUDY OPPORTUNITIES
Module Important terms and concepts
Boolean A value that is true (0) or false (1).
Class scope Refers to a variable that is declared in the private or public section
of a class definition. Can be accessed by all methods in the class.
Duration of a The lifetime – how long or when a variable exists in a program. When a
variable variable is declared in an event handler, it will be created when the
event handler executes, and will be destroyed when the event handler
is done being executed. Such a variable has local duration.
When a variable is declared as a public or private variable of the class
of a Form, it will exist all the time while the program is running. This
variable has static duration.
DIV An operator that gives the quotient of two values as a whole number.
File scope Refers to variables declared in the implementation section of the Unit file.
Method scope Refers to a variable that can only be used in a method, because
it is declared in the VAR section of that method.
MOD An operator that gives the remainder after the division of two values.
The ASCII character with the value 9 is the <tab> character. To place a <tab>
space between text in a Memo, you can use code such as the following:
memOut.Lines.Add('Name' + #9 + 'Mark');
Do not declare a variable with method scope with the same name as a variable with
class scope. Code in an event handler will always change the value of the variable
with the ‘nearest’ scope. It can be confusing if variables with different scope have
the same name.
STUDY OPPORTUNITIES
Chapter 2: Basic programs in Delphi 63
Module
Chapter 3
Custom subroutines
64
Custom
subroutines Chapte3
r
Introduction
! " # $ # $ % & $
! ! # $ ! ' !
( ) !
Containers of subroutines
! * $ ! !
+) !
! ( , , ( -) Code Units
, / ( $ Form Unit.
! Units !
! !
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs;
0 ! $ $ ! 1
!
, ( ! !
,
65
Module , $ ! ! )
! $ ! ' Math '
)
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Math;
2 !
5 (! !
$
'Power'.
5 (! # !
"
!
# $
7 8 7 98
: ! !
! $ ! # ;
! ) !
! <
! !
! " #
$
1
=
)
!
+) ! )
!", $ / # $ ! >? $
! ( , ! ) @
$ A>?A
66
Note:
5 1! $ ) ( , ! $ $ $
5 ! ! # ! ! ! $ / # )
arguments 1 # actual parameters.
; % &
$ $
parameters ! ;
!
arguments.
2 !! 1
, # !
! ! ! !
#
$
$
% # &% '% * "
" ! extended %
& @ "
$ 5 1 $
! ! $ ! ! ! C - $ % &
! ! )
+ - .. /0! 1 ! "
! Odd ! ! $
5 ! $ ! ! $ $ , !
)
+2 . +2 3 "
+5 #
6
.7
8 3 996
.
8 3 " 8 # <>? <
.8 * %<
.8 * %<
.8 * "
Module ; ! $ !
= 0 ! # F%F =
= +) )
! ) !
9 E$
var
sNote : string;
iValue : integer;
rValue : real;
cSymbol : char;
1 ! $ $ G (! $ $ !
& sNote := UpperCase(sNote); & @
A "
& @
8 8 " & sNote := Abs(iValue);
& @
3 97 - @
9% 9E
H
9% 9 9 "
H ; $ ! ! ! !
& Sqr & UpCase & Copy &
Activity 2: Use custom functions in a program
9 C frmDisplayInfo_p ! ! 1 $ #!
I ! ; # -* J K ! !
/
5 ! = % I % , ! && 5 I
* % ! &
5 ! %, ( ( , ! &
! $ # # #
68
Activity 3: Use the Help facility and teach one another
; # ! : ! ! $
D %9OPQ &
D %9OPQ H&
D %9OPQ >&
D %@?R ? H&
D %9R? &
+)
% >&
% @H&
%9O R ?&
%@HR H&
%HR @H&
+) +)
9 $ ! 1 ! ! !
H ; !
& S )2 V ) V
@ WX% 2
& @> &
)S
2a
& S H Y %ZV[&
!Z [ $
( $ 9QR
!
& S ?)P V H 9
& 1 9 HR % &
!& 1 ? 9? % &
69
!& R . # & 2% L
/% I " JJ6 H
L
. .
9 1 !
,/, ! # ! ,/, ! ! $ $ ! # C
1 H ; $
! ,/, D
H 0 # ( !] !
$ 1 ,< ( 0 DH?
% ! ! & % (! ! H
9 $ ! ^&
0 $ !
5 ! !
1 )- , the ceil !
5 ! 5 $ !
5 (
5 !
C ! $ ! ( !]
! ?RR ! ? ! D?Q ?R ;
! 1 ! 0
> ; !
5 ! % " * ! " * ! &
5 ! I #!
70
* ! $ *
? ; _ ! $
_ %0 !
5 " !
5 50 ! #% &
5 5 ! ! # !
! !
) " # #
$
1
=
)
! !
$ ! ) ` !
%! & $ , ! # $
. 8 T # . X "
begin
Randomize; JJ ! D ! # Beep" JJ #
8 # <>? <
.8 * %<
.8 * %<
.8 * " 8 < 5 "
Sleep(200); JJ ! H %HRR &
8 # <>? <
.8 * %<
.8 * %<
.8 * " 8 < 5 "
Beep; JJ #
ShowMessage(‘Disco done!’) ; JJ end ;
71
Module 5 ! $ 5 ! !
, # ! # %! ) # ,
&
1
Names of
1 $ $ I ! #! " !
$ !
!
! # %
&
!
72
. $ 8/ +..# . X "
var
iNumber, iAdd : integer;
begin
iNumber := sedNum.Value ;
iAdd := sedAdd.Value ;
Inc(iNumber, iAdd);
5-
2 78 "
end;
C ) ! ! !
9 2 'Z9"
Delete(sSentence, 9, 1); A( ^A
9 A( ^A
9% %0 "
73
Module
, # ! parameters.
$ 2 $ !
# ) 1L #
) $ !2 ?R
2
1 )- ! $
9 E$
var
sNote : string;
iValue : integer;
rValue : real;
cSymbol : char;
1 ! $ $ G (! $ $ !
& 7 *"
& T "
& Sleep(“tomorrow”);
& sNote := Abs(iValue);
H ; $ ! ! ! !
& Delete
&
& Val
Activity 8: Write Delphi programs using string functions and
procedures 9 ;
$ ! ! ! $ $ ! # C
Pos ! Delete $ " $
! !
H ; ! RQ>>R>>HH %
& $ ! VHPQ>>R>>HH
; I ! ! 00// $ ! 00003//3 0
L HRRR3R93R9
74
> ; )
5 , $ FRdI
% RdH Rd & !
FRd I ! %
L d& ) RdH RdHH RdO RdOO
; # !
%RdH&H>?O9H $ $
Study support
Advantages of subroutines
! " ! !#! !
5 # !
! 5 $
( ! ! ! # ) " ! $
5 #
0 $ " ( ! $ (!
!
5 $ ! !
0 ! ) I $
5 $ !
* $ ! !
75
1 ) ! ! A
$ 9
Form Units.
!
! programmer
for the
or
for th
e
/ ! $
Code Units.
!
the unit
name can
! ) ;
/ ,
- !
) ; Math, . . .
@ $
the unit
name can
1 or
!
@
"
!
Programming % ! E
9H &
! $
@ $
$ !
$ @
$
Object Oriented
76
The difference between subroutines and
methods &
"
programmer.
$ !
curriculum, but it will be used in
( , D D i Chapter 6 to demonstrate the
$ (
, ,
$ %
5 !
5 ! 5 ) " # # 5 $
5 ! " # ! !
5 $
$ ! "
*
@ % @ & ! !
` +) , 1 :
$ !
&'
77
, " * $ !
!
$ 1 ! ! ! " # $
' 1 ! " $ ! `
% ; $ $ "
covered in chapter 6.)
% 1 ! ! ) " # # $
! !
- 1 ! $ ! #
# !" $ ! !
! " # $
"
Unit 1 !
5 !
5
5 @ "
5 @ "
5
1 $ ! #
$ M
78
Chapter 4
Mastering decisions
and repetition in Delphi
79
Module repetition in
e
l
Delphi
u
d
Mastering Introduction
decisions and
o
M r
Chapte
4
! " # $ #
% & ' # (
procedure TfrmEven.btnDisplayClick(Sender:
TObject); var
iNumber : integer;
begin
Randomize;
iNumber := Random(20) + 1;
if iNumber MOD 2 = 0 then
begin
ShowMessage(‘Even Number’);
end;
end;
80