[go: up one dir, main page]

0% found this document useful (0 votes)
1K views101 pages

Delphi Grade 11 Textbook

Uploaded by

yveskanyinda8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views101 pages

Delphi Grade 11 Textbook

Uploaded by

yveskanyinda8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

Chapter

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.

IDE windows and toolbars


The IDE consists of a number of toolbars and windows. The windows can be moved around,
enlarged or minimised.

Tabs in the Component Palette


Component Palette
Title bar
Menu bar
Speed bar

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.

• The title bar and the menu bar


Save
are similar to the bars found in
Open Project
any Windows application.
• The speed bar consists of
several toolbars and provides
quick access to common
operations and commands. Open Run
The Form provides a place to

Chapter 1: Introduction to Delphi 3

Module The Form and components


The Form in Delphi is similar to the Stage in Scratch. In Scratch, you place Sprites on the
Stage as part of the user interface. These Sprites
are often used to display information, obtain input
Form
and produce output. Delphi provides components
such as Buttons, Labels, Edits, features and can perform specific
Panels, etc. that you can place on tasks.
the Form to perform these tasks. Labels
As previously mentioned, Delphi
is an Object Oriented Buttons
Programming language.
• Objects are entities which are
used when developing a Edits
program. Each object has specific Panels
• A component is a particular type of object that is used to create and control a user
friendly and interactive program interface.
• The names of all the components used in a specific Delphi application are shown in the
Object TreeView window in the Delphi IDE.
• Details about a component are shown in the Object Inspector (OI) window.
Let’s explore the Delphi IDE by looking at the Form.

Activity 1: Exploring the IDE and the Form

• 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.

The Component Palette


A toolbar called the Component
Palette is provided. The etc.).
Component Palette is divided into different If you move the mouse pointer across an icon, the
tabs (Standard, Additional, Win32, System, name of the component will appear as a tooltip.

Each tab contains a library of ready-made components that can be used in programs.

The Object TreeView


In this window you can see the current objects used in this program and
their names in a hierarchical view.
This Object TreeView shows you that this program contains two
components, a Form and a Button. The Button is placed on the Form.

Save and organise your Delphi


applications
Delphi creates a number of files for every new program. You should have a folder
structure in place to organise your work properly, otherwise your programs may not run,
or you may find it very difficult to find a specific program. We recommend that you
create a folder in which you can save all your Delphi programs. Inside this folder you
should create a folder for each program that you develop to keep the files that belong to
that specific program together.
When you save your program for the first time, you have to save two files – the Unit file
as well as the Project file.

Activity 2: Saving a Delphi program

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.

• Open the folder [First Program].


• Enter frmFirstProgram_u as the file name and
click [Save].
• Select (File | Save Project As) and save the project file with the name
frmFirstProgram_p.
• Keep Delphi open and also open Windows Explorer. Browse to the folder [First
Program] in Windows Explorer.
• How many files are there in the folder [First Program]?
• Switch to Delphi.
• Click on the [Run] Button (green arrow) in the Speed bar to run the program.
• Select (Run | Program Reset), or click ☒in the top righthand corner to terminate the
running program.
• Use Windows Explorer to determine the
number of
files which the [First Program] folder now contains.

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.

Activity 3: Use components to create an


interface
• Start Delphi.
• Open the Delphi application frmFirstProgram_p (File | Open
Project), open the folder [Delphi Programs Gr 11] and then
open the folder [First Program].
• From the Component Palette, select and place a Label, two
Buttons, a Shape and a Bitmap Button on the Form.

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.

• Change the properties of the Form and components in the OI as follows:


Shape Name shpCircle
Component Property Value
Shape stEllipse
Form Name frmFirstPro
Height 40
Font Comic Sans
Width 40
Height 330
Left 160
Width 350
Top 120
Caption My First De
Brush Color, clRed
Label Name lblMessage
Label Name lblMessage
Caption Click a Butt
Caption Click a Button
Button1 Name btnUp
Bitmap Button Name bmbClose
Caption Up!
Kind bkClose
Enabled True

Button2 Name btnDown


• Run the program.
Caption Down!
Components’ names
Enabled False
Components must have
descriptive names. You will use these names in your abbreviation that indicates the specific type of
programming code. Descriptive names will help you component you are working with, e.g. btn for a
to keep track of which components you are working Button, shp for a Shape, etc.
with in your code. We use the Hungarian naming • The second part is chosen by the programmer and
convention, i.e. should be descriptive of the purpose of the specific
• The first part consists of three letters, which is an component in the program.

• 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).

Chapter 1: Introduction to Delphi 7

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.)

Activity 4: Adding code

We are going to add programming code to the application frmFirstProgram_p to make it


perform a simple task when a Button is clicked. We want the following to happen:
- When the user clicks on the [Up!] Button, the red ball must move upwards. The [Up!]
Button must be disabled and the [Down!] Button must be enabled.
- When the user clicks on the [Down!] Button, the red ball must move downwards. The
[Down!] Button must be disabled and the [Up!] Button must be enabled.
• Open the application frmFirstProgram_p in Delphi.
Write instructions to be executed when the user clicks on a Button:
Let’s start with the [Up!] Button.

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.

Once you have entered the name of the component

• Delphi is a strictly-defined programming language and its rules must be followed to


the letter. If you do not type the code exactly as indicated, your program will not run. •
You can write comments anywhere in the program file by using any of the following
methods:
- Put // in front of a sentence which should be a comment.
- Enclose a paragraph in curly brackets { } or (* *) to comment it out. It is sometimes
useful to comment out certain programming statements while you are developing a
program and you cannot find an error. Comments can also be added to explain the
logic of a few lines of code. This will help you (or another programmer) when the
program needs to be updated.
• We can change the properties of a component in the OI before the application is
executed (statically). We can also change the properties of components through
programming code (or instructions) while the program is running (dynamically). •
The code that will execute when an event takes place is called the event handler.

Chapter 1: Introduction to Delphi 9

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>.

Structure of an event handler


The code in the previous example had to be executed when the Button was clicked. The
name of the click event is OnClick. The code itself is called the event handler. The
framework for the event handler is provided by Delphi and the programmer needs to enter
the code between the begin and end statements of the provided skeleton of the event
handler.
The relationship between a component, an event and an event handler can be illustrated as
follows:
pe, etc.) touch with the mouse (the code that must
has pointer, etc.) execute when the
For example: an event event is triggered)
A component which is linked to
(click/double click/
(Button/Label/Edit/Sha an event handler
procedure TfrmFirstProgram.btnUpClick
begin
shpCircle.Top := 10;
btnUp.Enabled := false;
btnDown.Enabled := true;
lblMessage.Caption := ‘Going
btnUp an OnClick up!’; end;
has linked to event

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

Unit file name frmFirstProgram_u

Project file name frmFirstProgram_p

Activity 5: Change a component’s properties in runtime

1. Work with the application frmFirstProgram_p again.


• Add some code to make the program more interesting, for example:
- Change the colour of the ball to yellow when it reaches the top position.
- Change the colour of the ball back to red when it reaches the bottom
position.
• Try and add code to create some other interesting effects by changing the
properties of the components, for example, change the colour of the Form as
well.
• Click on (File | Save All) to save the Unit and Project files.

2. Start a new application.


• Place one Button on the Form and change the caption to [Click me and see
what happens].
• Now write the event handler for the OnClick event of the Button to let the
following happen:
- When the user clicks on the Button, it should become larger and the words
[See how big!] should appear on the Button in a clear, large font.

Chapter 1: Introduction to Delphi 11

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).

3. Add a picture to an application.


• Start a new application.
• Place two Buttons on the Form ([Show] and [Hide]).
• Place an Image on the Form (this can be found on the Additional tab).
• To insert a
picture, click
on the three
dots next to
the
Picture
property
of
the Image
in the OI.
• Click on the
[Load]
Button in
the
Picture Editor to
choose a picture to
insert.
• To see the whole
picture in the
Image component,
set the Stretch
property to true.
• Complete OnClick event handlers for the Buttons to do the following:
- When Button [Hide] is clicked, the Image must disappear and when [Show] is
clicked, the Image must be visible again.

4. Start a new application.


• Place one Label and two Buttons on the Form.
• Write event handlers for the OnClick events of the Buttons so that the following
happens:
- The Label must turn red and show an appropriate message when the Button on
the left is clicked.
- The Form’s colour must change when the Button on the right is clicked.
• Save the application as frmLeftRightClick (i.e. the unit file should be saved as
frmLeftRightClick_u and the project file should be saved as
frmLeftRightClick_p).

5. Start a new application.


• Place two Buttons on the Form.
• Change the captions of the Buttons to Square and Rectangle.
• Complete the event handlers for the OnClick events of the Buttons. The Button
[Square] must change the height and the width of the Form to 200. The Button
[Rectangle] must change the height of the Form to 300 and the width to 100.
• When the Button [Square] is clicked, the Button [Square] must be disabled and
the Button [Rectangle] must be enabled and vice versa.

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.

The following statement is invalid: shpCircle.Top := false;


The data type of the Top property of a Shape is an integer value and refers to a position on the Form. The
word false is a Boolean value. It cannot be assigned to a property which can only receive integer values.
In the previous program we used properties with Integer, Boolean and String data types.

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.

Chapter 1: Introduction to Delphi 13

Module Activity 6: Identify syntax errors


1. Let’s make some errors to see what Delphi does:
• Open frmFirstProgram_p.
• Delete all the code after the begin statement of the event handler (even the end)
for the [Up!] Button and enter the following code exactly as displayed:
procedure TfrmFirstProgram.btnUpClick(Sender: TObject);
begin
shpCircle := 10
btnUp.Enabled = 'false';
Down.Enabled : = true;
lblMessage.Caption := Going up!;
• Run the program.
• A red bar will appear on the first line of the code with a long list of errors.
• The first error message says: Incompatible types: TShape and Integer.
The reason for this error is that no property has been specified. It should be
shpCircle.Top.
Correct the error and run the program again.
• The second error message indicates a missing operator or semicolon. Check the
end of all the lines to see where a semicolon should have been added. Correct
the error.
• The third message indicates that a ':=' was expected, but a '=' was found.
This error message clearly indicates the error. Correct it.
• The fourth message indicates that the word false should not be in inverted
commas.
Correct the error.
• The fifth message indicates that the name Down is unknown.
The name of our component was btnDown. Correct it.
• The sixth message is that the computer found a ':' when it expected a ':='.
The space between the ':' and the '=' caused this problem. Correct it.
• The seventh error message says the following: Undeclared identifier: Going!.
Going up! should have been used between inverted commas.
Change the line to the following: lblMessage.Caption := 'Going up!';
• The last error message tells us that the event handler does not end correctly.
All event handlers must end with end; Add the statement.
Your program will now compile.

2. Correct the following Delphi programming statements:


a) lblDisplay.Width := 50.5 ;
b) lblGreet.Caption := Hallo ;
c) btnGo := 'Click me!' ;
d) lblOutput.Enabled := 'False' ;
e) btnCalculate.Invisible := true ;

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.

Activity 7: Test your knowledge

Answer the following questions:

1. What is the advantage of a Rapid Application Development (RAD) tool such as


Delphi?
2. What is the skeleton code of a component together with the code added by the
programmer called?
3. What is the difference between changing the properties of components statically and
dynamically?
4. Answer the questions related to the following statement:
btnGo.Caption := 'Go!';
a) Name the component mentioned in the statement.
b Name the property of the component mentioned in the statement.
c) Name the value of the property of this component once the statement has been
executed.

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

Chapter 1: Introduction to Delphi 15

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

Edit Text String 'Hello World!'

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.

Activity 8: Call a component’s methods

• Start a new application.


• Create the following interface:
• The Button [Reset] should
- clear all the Edits
- hide all the Labels.
• Each Button’s event handler for the OnClick
event should
- show the Labels
- change the captions of the Labels to
display
the information in the relevant language
(You can choose any three languages.) - should be displayed.
place the focus in the edtName Edit. • Use the Retry BitBtn and change the caption
When the program starts, no Labels to &Reset.

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.

Activity 9: Place output strings in a component’s properties

• Start a new application.


• Place the following components on the Form: a Label (lblDisplay), Panel (pnlDisplay),
Memo (memDisplay) and a Button (btnDisplay). (They can all be found on the
Standard tab.)
• Change the Caption of the Button to Click Memo’); end;
Me. • Add the following code in the event
handler for the OnClick event of
btnDisplay:
procedure Notes:
TForm1.btnDisplayClick(Sender: TObject);
Change the values of the following properties
begin
of
lblDisplay.Caption := ‘This is output to a
the Panel in the OI: BevelInner, BevelOuter
Label’; pnlDisplay.Caption := ‘This is and BevelWidth.
output to a Panel’; Observe the effect thereof.
memDisplay.Lines.Add(‘This is output to a

• 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.

Chapter 1: Introduction to Delphi 17


Module Numeric output
In some cases, numeric values have to be displayed. The commonly used output
components can only display strings. Therefore, numeric values must be converted into
strings before they can be displayed by these output components.
Delphi provides functions to convert values from one format to another. A function is pre
programmed code that you can call to do certain calculations or operations and return a
result. The task of the functions IntToStr and FloatToStr are to convert a numeric value into
a string. The string is returned as a result.
The following code will perform calculations and will display the results on a Panel and a
Label.

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.

Use a dialog window to display output


Another way to make output appear on the screen is to
make use of dialog windows that will pop up code
and display the required output. This is done Note that event handlers are implemented as
by calling the ShowMessage procedure. A procedures.
procedure is a piece of pre-programmed

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:

ShowMessage(IntToStr(6 + 3 * 5)); ShowMessage(FloatToStr(6 * 12 / 7));


18
Activity 10: Create string, integer and real output

Start a new application and create the following interface:


Write code for the
event handler of the
OnClick event of each
Button. The answer created in the caption of the
to the calculation, Label by pressing <alt> and
typing 246.
as shown in the
caption of the Button, The squared sign (2) is created by
should be displayed pressing <alt> and typing 253.
in a dialog box (use Delphi has a built in function
the ShowMessage called PI that will return the
value of π. You can also use
procedure).
22/7.

Receive input
The ÷ character is

One of the most popular input components is the Edit. You


have viewed the Edit component in some of the prior
activities. The Text property of the Edit, which is a string data
type, contains the input.

String input from an Edit


Since the Text property of an Edit is a string data type and all output components can
display strings, no conversion is necessary when working with only string input and output.
In the following activity you will learn how to combine different input strings from the Edit
to create output.

Activity 11: Combine input strings

1. Create a new application and save the files as


frmGreet_u.pas and frmGreet_p.dpr. • Add the
• Create the following interface: following
• Change the Name property of the Form to code in
frmGreetMe. the event
handler for the OnClick event of the Button: begin
procedure
edtFirstName edtSurname btnClickMe
TfrmGreetMe.btnClickMeClick(Sender: TObject);

lblOutput.Caption := 'Hello ' + edtFirstName.Text + ' ' + edtSurname.Text; end;


• Run the program, then click in each Edit and type your name and surname in the
appropriate Edit.
• Click the Button [Click me please].
2. Open the program you created in Activity 8. Add code so the user will be greeted in
the language of his/her choice.

Chapter 1: Introduction to Delphi 19

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.

Activity 12: Combine input strings in a Memo

• Create the following interface


to
capture and display the
information
of the customers of a
company. (The
screen shot shows the
interface
when the program is
executed.)
• Group components in Panels to
improve the layout of the
interface.
(Hint: Place the Panels on the
Form first and then place the other
components on the Panels, such as
the Edits and Labels.)
• When the user clicks the Button
[Add], the information of the customer entered in the Edits must be displayed in the
Memo in the format indicated in the screen shot.
• Make use of the Clear and SetFocus methods of the Edit to clear the Edits and return
the focus to the Edit Name when coding the Reset BitBtn.

Numeric input from an Edit


Although some components have integer properties that can be used for the input of
integer values – we will discuss some of these components later – Edits are often used to
input numeric values. In an Edit, input
is always captured in the Text property
as a string data type. Therefore numeric
input added to the Edit needs to be
converted into a numeric data type,
such as an integer.
In the following example we will use a
new component – the Calender (on the be set to highlight a specific day in the year.
Samples tab) – to demonstrate how to The following code can be used to highlight
convert string input to numeric values. the date 25 December 2012:
The Calender component displays a grid Calender1.Day := 25 ;
on the screen with the names of the Calender1.Month := 12 ;
weekdays as column headers. Calender1.Year := 2012 ;
The Calender has three properties that can

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:

procedure TfrmDates.btnShowClick(Sender: TObject);


begin
Calender1.Day := StrToInt(edtDay.Text);
Calender1.Month := StrToInt(edtMonth.Text) ;
Calender1.Year := StrToInt(edtYear.Text) ;
pnlOut.Caption := 'This is the day of the week for ' + edtDay.Text + '/' + edtMonth.Text +
'/' + edtYear.Text ;
end;

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.

Numeric input from a SpinEdit


Delphi has a component, the SpinEdit (on the Samples page), that has an integer property
(the Value property). When you use this property, there is no need to convert the input into
in integer. Note that you cannot enter a decimal value into a SpinEdit.
The previous
program can then be
adapted as follows:
These are the SpinEdits.
Click on the arrows to
increase or decrease the
values. You can also click
in the SpinEdit and
enter the value, such as
2012, in the case of large
numbers.
If you want to display the
values in the SpinEdits in one of the output
components, you first have to convert the
integer values in the SpinEdits into strings.

Chapter 1: Introduction to Delphi 21


der: TObject); begin sedYear.Value ;
Calender1.Day :=
Module sedDay.Value;
Calender1.Month :=
procedure This converts integer values
TfrmDates.btnShowClick(Sen sedMonth.Value; into strings.
Calender1.Year :=

pnlOut.Caption := 'This is the day of the week for ' + IntToStr(sedDay.Value) + '/' +
IntToStr(sedMonth.Value) + '/' + IntToStr(sedYear.Value); end;

Activity 13: Numeric input

Open a new application and create the


interface shown here: (MaxValue and MinValue) that can be
Display the result of the operation in an Edit.
• When the user clicks on a Button, the
operation indicated on the Button should
be applied to the values in the SpinEdits.
(For example, sedValue1. Value or
sedValue2.Value.)
• Display the result of the operation in an
Edit.
• Hint: The SpinEdit has two properties
set to prevent the user from entering a value that is too small or too large. Set the
MinValue property of the second SpinEdit to 1 so a user cannot enter the value 0
(zero) and make the program produce an error when dividing the first value by the
second value.

Make components act on different events


Components can act on more than just an OnClick event.
When
you select a component and then click on the Events tab in
the
OI, you will see many events that the specific component
can
act upon.
To open the event handler framework for an event,
doubleclick
in the grey cell next to the name of the event, for example
the OnMouseMove event which is when the mouse pointer
touches the component.

22
Activity 14: Explore different events

1. Open the project frmGreet_p.dpr you created in


Activity 11.
• Change the Name property of the Form to
frmEvents.
• Create event handlers and add code to make the
following happen:
What should happen When should it happen

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);

Chapter 1: Introduction to Delphi 23

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

Object Specific car Edit has has has


* blue colour * Text=''
* Top=200
*
Attributes and MaxLength=13
(what it looks * OnClick
* OnChange
Behaviour
like) and * start
* stop and
* turn left
* turn right
Behaviour * accelerate Behaviour
(actions/what it can Attributes
(methods)
do/what it is used for) (properties and
Attributes events) * SetFocus

* 1600 cc engine * * Clear


* sports steering Name=edtInput * Show
wheel * Dunlop tyres * Width=40 * Hide

• 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 code for the class definitions of


components is placed in its own Units. We
cannot see that code. We can only see
what properties (attributes) and methods
(behaviours) of a component are available. edtName is an instance of class TEdit.
We change properties and call methods to
help us create and control an interface and

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;

Form1 is a variable declared as being of type TForm1. frmFirstProgram is a variable declared as


Once the program runs, Form1 is an instance of the class being of type TfrmFirstProgram. Once the
TForm1. program runs, frmFirstProgram is an instance
of the class TfrmFirstProgram.
Chapter 1: Introduction to Delphi 25

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.

Structure of the Form’s unit


When you develop a new program, Delphi provides certain code which you should never
delete. In the layout of a Unit below, the code that Delphi generates is shaded. This layout
also gives you an overview of all the sections in a Unit file. The window of the code editor in
Delphi is too small for you to see all the sections at once, so this should help you to obtain
an overview or the ‘bigger picture’.

26
unit frmBirth_u; interface The name of the unit that was decided on when you
uses saved the Unit file.

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,


Dialogs, StdCtrls, Grids, Calendar, ExtCtrls, ComCtrls;
type
TfrmDates = class(TForm)
Calendar1: TCalendar;
lblDay: TLabel; Class definition of the Form. It is considered a
lblMonth: TLabel; good programming principle to have only one
class definition per unit. The class is a new type
lblYear: TLabel;
of structure, so it follows the code word type.
btnShow: TButton;
pnlOut: TPanel;
edtDay: TEdit;
edtMonth: TEdit;
edtYear: TEdit;
procedure btnShowClick(Sender: TObject);
private
{ Private declarations }
public frmDates: TfrmDates; implementation
{ Public declarations }
end; {$R *.dfm}
The Form object's name.
var

Units used by the Unit file. These units are


libraries containing functions (such as IntToStr),
procedures (such as ShowMessage) and all the The event handlers and code are added in the
class definitions for the components and other implementation section.
objects used by Delphi itself.

procedure TfrmDates.btnShowClick(Sender: TObject);


begin
Calender1.Day := StrToInt(edtDay.Text);
Calender1.Month := StrToInt(edtMonth.Text) ;
Calender1.Year := StrToInt(edtYear.Text) ;
pnlOut.Caption := ‘This is the day of the week for ‘ + edtDay.Text + ‘/’ +
edtMonth.Text + ‘/’ +
edtYear.Text ;
end;
The end of the unit.
end.

Chapter 1: Introduction to Delphi 27

Module Improve and test your


knowledge and skills Overview of
knowledge in this module

• 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

Chapter 1: Introduction to Delphi 29

Module Important terms and concepts


Component A particular type of object that can be placed on the screen and
which can perform interactive activities.

Computer Program A series of instructions written in a language understood by


the computer that tells it exactly what to do.

Event It is a special property linked to code (event handlers) which is


executed whenever a particular action occurs. The action can be
detected by a program. This includes actions performed by a user
(such as clicking the mouse button), or system occurrences (such
as reporting an error when a division by zero operation was
made).

Event handler Code that is linked to a component’s event and which is


executed when the event is triggered.

IDE Integrated Development Environment

Method Pre-written code associated with an object that performs a


specific task. Used to describe an object’s behaviour.

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.

OOP Object Oriented Programming

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.

RAD tool Rapid Application Development tool

Syntax error An error that occurs when the rules of the programming language
are not followed.

Tips and recommendations


Place multiple copies of a component on the Form
Hold <shift> down when you click on the component in the palette. Every time you click on
the Form you will place another instance of the component on the Form. To stop placing
components, click the mouse pointer at the start of the palette.

Change the dimensions of a component – three different ways


1. Click on the component and use the handles to drag and resize the component.
2. Change the properties in the Object Inspector.
3. Change the properties through code in an event handler.
Display the Object TreeView or the Object
Inspector
If any of the parts of the IDE are not visible, you can
use
the View command on the menu bar to display the IDE
again.

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.

Save the .pas and .dpr files


You can click on the Save All icon or menu option when you want to save your files. Delphi
will automatically prompt you to save the unit file first and then the project file.

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.

Delete one line of code at a time


Click anywhere in the line of code you want to delete. Press <ctrl> and <y>

simultaneously. Move a component from a Form onto a Panel

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.

Chapter 1: Introduction to Delphi 31

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.

Practical module activities


1. Imitate a traffic light
Start a new application.
• Place the indicated components on the Form and change the properties in the OI as
follows:
Top 100
Component Property Value
Height 100
Form1: Name frmTraffi
Width 75
Caption Traffic lig
simulato Button3: Name btnGreen

Color clBlack Caption &Green

Height 350 Left 0

Width 225 Top 200

Button1: Name btnRed Height 100

Caption &Red Width 75

Left 0

Top 0

Height 100

Width 75

Button2: Name btnYellow

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

Shape2: Name shpYellow

Shape stCircle

Left 100

Top 120

Height 65

Width 65

Shape3: Name shpGreen

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.

2. Alternative traffic light


The properties of the components can also be set using code in the event handler of the
OnCreate event of the Form instead of the OI. For example:
with frmTrafficLight do
begin
Color := clBlack;
Height := 338;
Width := 200;
end;

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.

Chapter 1: Introduction to Delphi 33

Module 3. More Buttons


• Place four Buttons and an Edit on your Form.
• Change the captions of the Form and the components
as indicated.
• Change the Font of the Form to Comic Sans MS, the
Font Style to Bold and the Font Size to 12. (Click on the
three dots next to the Font property to open the Font dialog box where the Font,
Style and Size can be selected. The Font properties of all the components will inherit
the values of the Font property of the Form.)
• Write the following OnClick event handlers for the Buttons:
btnColour Change the colour of the Form to SkyBlue.
Change the colour of the Edit to MoneyGreen.
Change the colour of the font of the Edit to red.
btnFont Change the font size of the Form to 10.
btnFormSize Change the width of the Form to 300.
Change the height of the Form to 200.
btnPos Change the positions of the components on the Form.

4. The MouseMove event


• Start a new application.
• Place the following components
on the Form named
frmMouseMove:
- pnlSlave
- pnlGreen
- pnlRed
• Change the captions in the OI as
indicated.
• Change the Color properties of
pnlGreen and pnlRed as AB
indicated.

• 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.

• Now add an event handler for the

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.

Identify input, processing and output


From your experience with Scratch, you know that most programs can be divided into
three sections:

Input Processing Output


• Process the data, e.g. by and making
• Get the data that will be doing comparisons.
used in the program. calculations • Display the results.

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

TASK: Calculate the price of the tickets


BEGIN
Ask ‘The name of the learner’
Get Name
Ask ‘Number of tickets to buy’
Get NumberOfTickets
AmountPayable🡨 NumberOfTickets x 5
Display Name, ‘ you need to pay ‘, AmountPayable
END

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

Name AmountPayable🡨 NumberOfTickets x 5 Name


NumberOfTickets AmountPayable

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:

Input (from Edit Boxes)

Processing (instructions in the event handler


of the Button's OnClick event)

Output (on a Panel)

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

• Output of a program is assigned to properties of components suitable for


output, such as the Caption property of the Panel (in this case) or the Text
property of an Edit, or the Caption property of a Label.

Activity 1: Draw IPO tables

Do the following for each of the algorithms provided:


a) Create an IPO table including suggested components to be used.
b) Draw a diagram showing the layout of the interface you will create to solve
this problem.
STUDY OPPORTUNITIES

38 Chapter 2: Basic programs in Delphi


1. TASK: Carpet calculations
BEGIN
Ask 'What is the radius of the round carpet?'
Obtain Radius
Ask 'What is the cost per meter?'
Obtain CostPerMeter
Circumference 🡨2 x Pi x Radius
Area 🡨Pi x Radius x Radius
TrimmingCost 🡨Circumference x CostPerMeter
Display 'The amount of trimming required: ', Circumference
Display 'The area the carpet will cover: ', Area
Display 'The cost for trimming is R ', TrimmingCost
END

2. TASK: Convert Pounds to Rand


BEGIN
Ask 'What is the amount in pounds?'
Obtain Pounds
Ask 'What is the exchange rate?'
Obtain ExchangeRate
Amount 🡨 Pounds / ExchangeRate
Display 'The amount is R ', Amount
END

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

Module Examples of variable declarations in an event handler


procedure TfrmMarks.btnCalculateClick(Sender: TObject);
var
iCount : integer;
sName : string;
rAverage, rTotal : real;
begin Variables can also be declared in the public
//Code of the event handler will be entered declarations part of a class. We will learn more
here end; about this in the section on the scope of
variables.

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.

Rules for variable names


• The name has to start with a letter or an '_' (underscore sign).
• The name may not contain spaces.
• Letters, numbers and the underscore sign are allowed after the first character.
(The only special character that may be used is the underscore sign.) • A name
may not be a key word or a reserved word (a word that is used by Delphi and
already has a specific meaning, e.g. begin, var, end, etc.). • Only the first 255
characters of the name will be considered as meaningful. • Multi-word variable
names are probably the most effective in describing the contents of the variable.
Write them with a capital at the start of each word – e.g. FirstName, TotalCost.

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.

Activity 2: Identify invalid variable names

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

40 Chapter 2: Basic programs in Delphi


STUDY OPPORTUNITIES
Variable types
The simple variable data types which we will use, also known as primitive data types,
are integer, real, char, string and boolean.

Activity 3: Choose variable names and data types

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:

rAns := iNumA + iNumB ;


rValueA * 4 ;
Can be assigned Result is of data type integer
to a real data type

But this is invalid: iAns :=

• 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:

iAns := iNumA MOD iNumB; iAns := iNumA DIV iNumB;

Expression How it works Result Expression How it works Result

10 MOD 3 10 divided 10 DIV 3 10 divided by


1 3
by 3 = 3 3 = 3. Discard
remainder 1 the remainder
of 1.
12 MOD 2 12 divided
0 12 DIV 2 12 divided by
by 2 = 6 6
remainder 0 2=6

23 MOD 6 23 divided 23 DIV 6 23 divided by


5 3
by 6 = 3 6 = 3. Discard
remainder 5 the remainder
of 5.

42 Chapter 2: Basic programs in Delphi


STUDY OPPORTUNITIES
Activity 4: Ensure that data types are compatible

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;

b) iAns := iNum DIV 3; i) iNum MOD 20 := iNum;

c) rAns:= iNum DIV iAns; j) iNum := edtNumber.Text;

d) rAns := iNum MOD iAns; k) cChar := edtLetter.Text;

e) inc(iNum,5); l) sLine := sedNumber.Value;

f) inc(rNum); m) sLine := sedNumber.Value;

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

Second * / DIV MOD (Executed from left to right.)

Third +-
The following table shows a comparison between calculations coded in Scratch and
Delphi.
rAns := iB + iA / 2;

rAns := (iB + iA) / 2;

rAns := ((iA / iB) + iC) /


2;

rAns := (iA / (iB + iC)) * 2;

Activity 5: Working with numerical operators

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

1. Calculate one quarter of the iValue := sedA.Value + sedB.Value / 4;


sum of two values.

2. Calculate the average of 2 values. iCount := 0 ;

iTotal := sedMark1 + sedMark2 ;

rAvg := iTotal / iCount ;

3. Calculate the sum of two values iSum := sedValue1 + sedValue2 ;

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.

Use the FloatToStrF function to format output


pnlOut.Caption:= FloatToStrF(rVal,ffFixed,6,2);
FloatToStrF(Value, Format, Total number of digits, Number of decimal digits)

Formats allowed Description

ffCurrency Formats the value with the currency included.

ffExponent Formats the value in scientific notation.

ffFixed Formats the value with the number of decimals as specified.


ffGeneral General number format. Includes decimals only when required.

ffNumber Corresponds to ffFixed, but uses thousands separator.

STUDY OPPORTUNITIES
Chapter 2: Basic programs in Delphi 45

Module Activity 6: Plan and write Delphi programs


1. Work in groups of two. One member should write code in Delphi, and the other
member should write down the results.
Type the following code in the event handler of the OnClick event of a
Button: rValue := 456.8857485;
ShowMessage(FloatToStrF(rVal,ffFixed,6,2));

Draw the following table to record the information:


Value Format Number of Decimal digits Display
digits

456.885748 ffFixed 6 2 456.89


5

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.

2. You buy three items at a shop. Calculate the total


price and display the items bought, the following algorithm:
prices of the three items, the total Get Mark1, Mark2, Mark3
price, the VAT to be added and the final Average 🡨 (Mark1 + Mark2 + Mark3) / 3
amount.
Display Name, Average
3. Enter the name of a learner and the The interfaces for activities 2 and 3 are
marks (as percentages) of three IT tests available with the data for the book. Open
written by the learner. Determine the the programs and complete the code in
average of the three marks. Display the the event handlers.
learner’s name and average. Use the
Programmers are often tempted to start programming without planning the solutions
first. This approach is not advisable! You have to discipline yourself and always plan the
solutions before you start to code. The next activity contains programs similar to those
you did in Scratch. However, you need to think about the solution and the different
components you want to use. Therefore take time to create IPO-tables first before you
start programming.
STUDY OPPORTUNITIES

46 Chapter 2: Basic programs in Delphi


Activity 7: Plan and write Delphi programs

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

iLength, iWidth iPerimeter 🡨 2 x iLength + 2 x iPerimeter


iWidth iArea !iLength x iWidth iArea

INPUT COMPONENT(S) OUTPUT COMPONENT(S)

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.

4. Mrs Botha makes Cremora tarts for a Home Industries shop.


a) She often makes more than one tart and she needs to know how to adapt the
ingredients for any number of tarts. When she enters the number of tarts, the
program should display the new quantities of ingredients required.
Ingredients for one tart:
250 ml Cremora
125 ml boiling water
1 tin (397 g) condensed milk
125 ml lemon juice
b) The lemon juice bottles come in quantities of 330ml and 500ml. Mrs Botha
wants to enter the quantity of lemon juice in a bottle into the interface of the
program, and then the program should display the number of Cremora tarts
(displayed as a whole number) that could be made with one bottle of lemon
juice. The program should also calculate the remaining millilitres of lemon
juice.

5. Calculate the number of different notes


and rand coins you would require to
make
up an amount greater or equal to R1
and
less or equal to R200. Use a SpinEdit
for the
input. (Hint: Set the Minvalue property of the
SpinEdit to 1, and the MaxValue to 200.)
Chapter 2: Basic programs in Delphi 47

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

8. Nthabiseng started a small catering business. She needs an application to


calculate the number of people she can serve if she enters the number of grams
she has prepared of a specific dish. The application must calculate and display the
number of full portions of the particular dish she can serve as well as the leftover
volumes in grams.
The average amount of food per dish to serve one person is as follows:
385 grams of cooked meat
145 grams of side dish
120 grams of salad greens
190 grams dessert serving

Use the InputBox function for input


Advantage: No need to place a component on a Form for input. The InputBox appears when the
program is executed
label prompt string default value

sGender := InputBox('Gender', 'Enter the gender (Male/Female):', 'Female');

This single line of Delphi code, generates the following dialog box:

• The default value can also be blank (see examples below).


• An InputBox function always returns data as type string.
The following examples show how to convert the string result returned by the InputBox function
into other data types if required and assign it to a suitable variable.

Required data type Example

string sAddress := InputBox('Address', 'Enter the address ','');

integer iCount := StrToInt(InputBox('Amount',' Enter the amount:',''));

real rSales := StrToFloat(InputBox('Sales',' Enter the sales figure:',''));

char cClass := InputBox('Class',' Enter the class:','')[1];


The [1] following the closing round bracket instructs Delphi to use only
the first character of the string returned by the InputBox.

48 Chapter 2: Basic programs in Delphi


STUDY OPPORTUNITIES
Activity 8: Obtain input using the InputBox function

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.

The interfaces for activities 1 and 2 are


available with the data for the book. Open
the programs and complete the code for the
relevant event handler(s).

2. Write a program to display an itemised quotation of bookings at a guest house.


When the user clicks on the Button [Number of rooms], an InputBox should be
displayed requesting the number of rooms that has to be booked. Calculate the
total price for the rooms, at R450.00 per room and display the price in currency
format in a Panel next to the Button. Do the same for the number of breakfasts (at
R60.00 per breakfast) and number of dinners (at R120.00 per meal).

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.

Activity 9: Use constants and variables

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

50 Chapter 2: Basic programs in Delphi


program is running and not only while the event handler is being executed. These
variables cannot be declared inside the event handler but should be part of the
declaration of the Form. The following is an example of such an application:
A number of school bands had their favourite songs recorded, and they want their
fans to choose the winning DVD. A Delphi program can be used to ask the learners
to cast their votes by selecting their favourite of the three DVDs. Each time a
learner clicks on an image, the total votes for that DVD is incremented by one vote.
The number of votes casted for each cover is displayed in the panels below the
images.
Interface design:

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.

2. The IT teacher has to collect money


for a
class trip. Learners come at irregular
times
to make payments. Learners who
want to
can pay more than the prescribed
amount
to support some of the learners who
are
unable to pay. She wants a program
that
will enable her to enter the amount a
learner pays and click a Button to process
the payment. The program should display
the number of learners who contributed
so far, as well as the total amount
received so far.

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

52 Chapter 2: Basic programs in Delphi

iTotal is displayed on the panel.


Since all three event handlers must be able to change the contents of the variable
iTotal, the variable iTotal cannot be declared in any of the event handlers because
then:
• only the one event handler where iTotal is declared will have access to the variable,
and
• iTotal will have local duration, so its contents will be lost once the event handler is
done being executed.
The solution is to declare the variable in the private declaration section of the Form’s
class (as we did in the previous example). In this way it becomes part of the attributes
of the Form – we say it has class scope. This means all the methods (therefore event
handlers) of the Form will have access to the variable iTotal. The code for this program
includes the following:

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

begin begin begin


iTotal := iTotal + 10; iTotal := iTotal + 20; iTotal := iTotal + 50;
pnlOutput.Caption := pnlOutput.Caption := pnlOutput.Caption :=
'The total amount raised 'The total amount raised 'The total amount raised
is now: R ' + is now: R ' + is now: R ' +
IntToStr(iTotal); IntToStr(iTotal); IntToStr(iTotal);
end; end; end;

Event handler for the OnActivate event of the


Form Even though Delphi will initialize the values of all
the variables of the class, it is always better to
begin make sure it is done where and when you want it
iTotal := 0; done by initializing the variables yourself.
end;

Chapter 2: Basic programs in Delphi 53

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

Sprite scope Method scope


• Variable declared For • Variable or constant is declared in the var section
this sprite only. of an event handler (a method of the Form’s class).
• Only the Sprite can access • Only the event handler can access the variable or
the variable. constant.

Variables or constants with method scope


have local duration.
Stage scope Class scope (demonstrated in the example that
• Variable is declared For follows) • Variable is declared in the private or
all sprites. public section of a class definition. (For the type of
• All the sprites on the Stage programs we are writing, it will be declared in the
can access the variable. private section of the Form’s class definition.)
(Open the FastFoods.sb • The variable becomes an attribute of the Form,
program provided as data with and all methods of the Form will be able to access
the book to revise your the variable. (In the programs we wrote up until
knowledge of the use of Stage now it would be all the event handlers of the Form.)
scope variables.)
Variables with class scope have static duration.

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.

Variables and constants with file scope


have static duration.

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

54 Chapter 2: Basic programs in Delphi


item the user wants to order(using an InputBox function), and calculate the cost for
the items. A user must be able to order more than one item, and click on an icon (a
calculator) to indicate that the order is complete. The total amount due as well as the
number of each item ordered must then be displayed. (An .exe file for this program is
provided as part of the data for the book.)
The following example shows part of the program (the code for one of the three
items’ event handlers):
A variable, iCount (integer),
keeps track of the total
number of items ordered.

A variable, rTotalDue (real),


keeps track of the total amount
due.

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;

procedure imgHamburgerClick(Sender: TObject);


procedure imgPizzaClick(Sender: TObject);
var
procedure imgCooldrinkClick(Sender: TObject);
Form1: TfrmFastFoods;
procedure imgCalculatorClick(Sender: TObject);
Variables with private class scope. They are accessible
procedure FormShow(Sender: TObject); private from all five event handlers. We could have declared
iCount : integer ; the variables with public scope as well. That would
rTotalDue : real ; enable other forms to use and see the variables
public should the project contain more than one Form.
{ Public declarations } However, it is not relevant for this program.
end;
Chapter 2: Basic programs in Delphi 55

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:

'Click on the calculator to show the total amount due';


iCount := 0 ;
rTotalDue := 0 ; end; The variables with class scope can be accessed by
all the event handlers.
end.

Activity 11: Use variables with class scope

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.

2. Write a program to assist a teacher with the calculation of marks.


She must be able to
• specify the maximum marks a learner could have achieved (this will be done
once only)
• enter each learner’s mark.
STUDY OPPORTUNITIES
56 Chapter 2: Basic programs in Delphi
The program must
• display the percentage of each
mark
• display the updated number of
marks entered
• display the updated class
average
with no decimal values.
• have a [Next class] Button to
clear
all values and allow marks of
another class for another test to be
entered.

3. Update the guest house quotation program (activity 8 number 2) to calculate


and display the total amount of the quotation as well. Add a Bitmap Button
[Reset] that will clear all the values to allow the next guest to obtain a
quotation.

4. Write a program to assist a security company to keep track of the number of


vehicles entering and leaving the parking area at a shopping mall. Hint: When
a vehicle leaves the parking area, the variable keeping track of the number of
vehicles in the parking area must be decremented by one.

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

58 Chapter 2: Basic programs in Delphi


We can now complete the TOE chart by filling in the events associated with each task
and object:
Task Object Event

Obtain the number of items sedNumItems Exit


bought Calculate the cost of all btnBuy Click
the items Display the cost btnBuy, memCashSlip Click, None
Obtain the amount the customer btnShowChange, edtPaid Click, None
paid Calculate the change btnShowChange Click
Display the amount of change btnShowChange, memCashSlip Click, None

The steps in designing a TOE chart can be summarized as follows:


1. Identify the tasks The task Display the cost involves two objects –
2. Assign an object to each task a Button and a Memo. The cost should be
displayed when the user clicks (an event) on
3. Add events btnBuy, but no event is associated with
memCashSlip – it is used to display the
information. Therefore the entry in the TOE
The TOE chart is one of the tools that chart is as follows:
can be used in designing object
oriented applications. Remember that
btnBuy, memCashSlip Click, None
you might not always be instructed to

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

Module procedure TfrmRegister.sedNumItemsExit(Sender: TObject);


begin
iNumItems := sedNumItems.Value;
end;

procedure TfrmRegister.btnShowChangeClick(Sender: TObject);


var
rPaid, rChange : real ;
begin
rPaid :=StrToFloat(edtPaid.Text);
rChange := rPaid - rAmount ;
memCashSlip.Lines.Add('Paid : ' + FloatToStrF(rPaid,ffCurrency, 8, 2)) ;
memCashSlip.Lines.Add('Change : ' + FloatToStrF(rChange,ffCurrency, 8, 2)) ;
end;
end.

Activity 12: Plan a program using a TOE chart

1. Work in groups of two:


Create a TOE chart to expand the program in the example of a TOE chart to
include the following:
• Change the caption of btnBuy to No discount
• Add a Button [Pension]
• Add a Button [Loyalty card]
• Add a Bitmap Button [Next customer]
If the client is a pensioner, 10% discount on the cost of items should be given.
Loyalty card customers receive 5% discount. The Button [Next customer]
should clear all components and provide the opportunity for a new customer’s
data to be entered.

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

60 Chapter 2: Basic programs in Delphi


Add a [Register] Button to display the following information in a Memo
component:
The name, Grade 12 mark, the initial class fee, the distinction fee, the
residence fee, the bursary fee and the final fee. The value of zero is displayed
if a fee is not applicable.
When the user clicks on the [Next student] Button all the information must be
cleared to allow another student to register.

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

• Variables can be accessed by


different parts of a program,
• The name of a variable refers to the • Represented in hexadecimal •
address of the variable in memory. Different variables are stored at
Scope
• There are rules for naming variables. different locations in memory.
Name
Memory
Address
• The lifetime of
a variable.
Duration Variable

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

memory. • Different data types in


Delphi, such as integer, real,
char, string, boolean, etc.
• The value of a variable
must be compatible
with the data type of
the variable.
Chapter 2: Basic programs in Delphi 61

STUDY OPPORTUNITIES
Module Important terms and concepts
Boolean A value that is true (0) or false (1).

Char A value that consists of one character.

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.

Constant A fixed value allocated to a variable in a program.

Data type Indicates the type of data to be stored in a variable.

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.

FloatToStrF A function used to format output, for example:


pnlOut.Caption := FloatToStrF(rVal, ffFixed, 6, 2);

InputBox A function that generates a dialog box to obtain input, for


example: sName := InputBox('Type the name:','Name:','');

Integer A value of this type can only be a whole number.

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.

Real A value of this type can be any number.

Scope of a The part of a program where a variable can be accessed. So far we


variable have worked with variables and/or constants that have:
• Method scope: Variables or constants declared in an event
handler. Can only be accessed by the specific event handler.
• Class scope: Variables declared as a private variable of a class. Can
be accessed by all the event handlers of the class.
• File scope: Constants declared in the implementation section of
the unit. Can be accessed by all event handlers in the same unit.
(In our programs a unit contains only one class, therefore we can
also say these constants can be accessed by all event handlers in
the class defined in the unit.)

String A data item that consists of a combination of characters.


Variable A space in RAM where a data item can be kept temporarily.

62 Chapter 2: Basic programs in Delphi


STUDY OPPORTUNITIES
Tips and notes
You can make text appear on 2 lines of a Label’s caption, by using the character
#13 (ASCII code for carriage return – which is <enter>). For example
lblOut.caption := 'This is line 1' + #13 + 'This is line 2' ;

will result in the following Label:

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 !

rValue := Power(iNumber, 4) ; 33 %2 &4

5 (! !
$

'Power'.
5 (! # !
"
!
# $
7 8 7 98
: ! !

! $ ! # ;

! ) !
! <

Rules and terminology


regarding functions
1

! !
! " #
$
1
=
)
!

+) ! )

!", $ / # $ ! >? $

! ( , ! ) @
$ A>?A

66

$ >? $ >? $ A>?A

Note:
5 1! $ ) ( , ! $ $ $
5 ! ! # ! ! ! $ / # )
arguments 1 # actual parameters.

; % &

$ $
parameters ! ;
!
arguments.

2 !! 1

, # !
! ! ! !

<variable> := <Name of function > (<argument(s)>);


5 ! ! " ! ( , ! ! ) =
! 1 ) ! ! !

#
$
$
% # &% '% * "
" ! extended %

& @ "
$ 5 1 $
! ! $ ! ! ! C - $ % &
! ! )
+ - .. /0! 1 ! "

! Odd ! ! $

5 ! $ ! ! $ $ , !
)

+2 . +2 3 "
+5 #
6
.7
8 3 996
.
8 3 " 8 # <>? <
.8 * %<
.8 * %<
.8 * "

The Uppercase ! $ * ! * DE- ! $ % D -


& $ ! ! D E -
67

Module ; ! $ !
= 0 ! # F%F =
= +) )

! ) !

The copy ! = ' % ! & $ % ! !


&
1 )- ) ! ( ) $ #
1 )- ! $

Activity 1: Answer questions about custom functions

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

; # ! : ! ! $

5 E 9 RoundTo ! double. 5 E H Power !


extended.
+ ! 1L )
1L "
! M
Result

D %9OPQ &

D %9OPQ H&

D %9OPQ >&

D %@?R ? H&

D %9R? &

+)

% >&

% @H&

%9O R ?&

%@HR H&
%HR @H&

+) +)

Activity 4: Use mathematical functions

9 $ ! 1 ! ! !

/I !" * " *"


& +
1 J
K" & +
1 J
K K< .
1 J" & + < .+ .H#K
K " & + A /!! J A
" & + < . A
K "

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

Module Activity 5: Use string functions


9 ; ! ! ! ! 2 9 H 2
88 29"
& L L 99% 2"
& iL := Length(sString);
& L L 9 2
& sWord := Copy(sString,3,4);
89% 2" D 1
& L )-
L 9 9% 2 " JJ .

!& R . # & 2% L
/% I " JJ6 H
L

. .

Activity 6: Use custom functions in programming code

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 ! ! # !

Rules and terminology


regarding procedures
1

! !
) " # #
$
1
=
)
! !

$ ! ) ` !
%! & $ , ! # $

Procedures that perform tasks


< # ! ) ' I $ ! #

. 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

Procedures that return


results
$ +) !
)

. $ 8/ +..# . X "
var
iNumber, iAdd : integer;
begin
iNumber := sedNum.Value ;
iAdd := sedAdd.Value ;
Inc(iNumber, iAdd);
5-
2 78 "
end;

The Inc ) ' 2 1 -! "


( $ ! 2 HR $ ! 1 ; # var ! !
( ) 2 reference
%$ &
$ !H $ ! 1 ! !
( ! $ 2 ; ! address of
; % & the !
$ ! $ C
$ # b1D ! ! $ %& (! $ !
Inc( @ !
I $ # var
! !
value parameter.

; $ parameter, the value !


sedNum sedAdd ! # ! $ $ !
M

C ) ! ! !
9 2 'Z9"

Delete(sSentence, 9, 1); A( ^A

9 A( ^A
9% %0 "

73

Module
, # ! parameters.

$ 2 $ !
# ) 1L #
) $ !2 ?R
2

1 )- ! $

Activity 7: Determine the correct use of procedures

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

Module Overview of the use of Units


! M ! $ $ ! !

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

Module Important terms and concepts


& (& ) " * " ! +

, " * $ !
!

$ 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
! " # $ #
% & ' # (

The If .. then and If .. then .. else


statements
If statements in Scratch and Delphi
! ) * ) * # +
, ) * & ( ( - )
* . & , begin and end (
if .. then

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

You might also like