IT Practical Book Grade11
IT Practical Book Grade11
digital books.
ISBN 978-1-928388-53-1
First published in 2019 © 2019. Copyright in the text remains with the contributors.
Allison Philander, Carina Labuscagne, David Peens, Denise van Wyk, Edward Gentle,
Jugdeshchand Sewnanen, Julian Carstens, Magdalena Brits, Shamiel Dramat, Shani
Nunkumar and Zainab Karriem
Restrictions
You may not make copies of this book in part or in full – in printed or electronic or audio or
video form – for a profit seeking purpose.
Introduction
Unit 1.1 Errors, debugging and mathematical methods
Unit 1.2 Mathematical methods
Consolidation activity
Introduction
Unit 2.1 Nested loops
Unit 2.2 Using nested loops
Unit 2.3 Creating shapes using nested loops
Consolidation activity
Term 2
Chapter 3 Arrays
Introduction
Unit 3.1 Arrays
Unit 3.2 Searching and sorting arrays
Unit 3.3 Parallel arrays
Consolidation activity
Introduction
Unit 4.1 Built-in string methods
Unit 4.2 Delimited strings
Unit 4.3 Built-in Date-Time methods
Consolidation activity
Term 3
Introduction
Unit 5.1 Introduction to text files
Unit 5.2 Reading from a text file
Unit 5.3 Writing to a text file
Unit 5.4 Creating reports
Consolidation activity
Introduction
Unit 6.1 Introduction to user-defined methods
Unit 6.2 Procedures
Unit 6.3 Functions
Unit 6.4 Basic input validation techniques
Consolidation activity
Introduction
Unit 7.1 Multi-form user interfaces
Unit 7.2 Dynamic Instantiation of objects
Chapter 8 Databases
Introduction
Unit 8.1 Creating a database
Unit 8.2 Connecting to a database
Unit 8.3 Reading data from a database
Unit 8.4 Writing data to a database
Unit 8.5 Manipulating data
Consolidation activity
Glossary
QR Code list
Dear Learner
Welcome to the IT Practical Grade 11 textbook, and welcome to
programming.
If this is your first time learning how to program, don’t worry. This
textbook has been designed to teach anyone – regardless of
experience – how to program. If you follow along with all the examples
then you will be an experienced programmer who has written more
than 50 programs by the end of this book.
To give you the most opportunities to learn, this book will give three
types of programming activities:
Examples
Examples will guide you through the creation of a program from start
to finish. All you need to do with examples is to follow the step-by-step
guidance provided to you.
Guided activities
Guided activities have a program that you need to create on your own.
Your teacher will provide you with the solution. These solutions should
be used as an opportunity to compare your program, and to see
where you may have made errors or left something out.
Activities
Activities are programs that your teacher can give to you as classroom
activities or homework. With these programs, you will only be
assessed on how well your program works, so use your creativity to
come up with a solution!
New words
These are difficult words that you may not have encountered before. A
brief explanation for these words are given.
QR Codes, Videos and Screen captures
These will link you to online content. When you are in the eBook, you
can easily access the links.
Consolidation activities
This is a revision activity based on what you have covered in the
chapter. Take time to answer the questions on your own. You teacher
may also use these to assess your performance during class.
CHAPTER UNITS
Learning outcomes
INTRODUCTION
This chapter serves to consolidate all the knowledge you acquired in
your Grade 10 studies (also see Annexure A for more Grade 10
revision). It also focuses on new content that includes work on
mathematical methods. You will use these mathematical methods to
solve problems during this year.
UNIT
1.1 Errors, debugging and validation
Programming errors can generally be grouped into three categories:
syntax errors, runtime errors and logic errors.
WHAT’S AN ALGORITHM?
https://www.youtube.com/watch?
v=6hfOvs8pY1k
With Delphi, RAD Studio will provide you with information on the error
in the Structure panel at the top left Code screen, as well as in the
compiler when you try to run the program. Double clicking on the
mistake in the Structure panel will jump to the line with the problem.
Figure 1.1: The Structure panel will inform you of most syntax mistakes
Runtime errors occur when you ask your program to do a task that is
either impossible or is impossible under certain circumstances. In most
instances, runtime errors will cause your program to crash. Runtime
errors can occur in almost any program, but some examples include:
Doing mathematical calculations on strings.
Performing illegal mathematical operations (such as dividing
numbers by 0)
Reading and using values from empty textboxes.
Reading a list value that has not been created.
Activating a ListBox’s OnClick event when nothing is selected.
Combining strings and numbers without changing their data types.
One way to solve a runtime error is to step through your program. You
can also search for the error code online to see if it helps you to
identify the cause of the error.
The final, and most difficult errors to solve are logic errors. These errors
occur when there is a logical error or design problem in your program.
While logic errors can cause applications to crash or give error
messages, the program can also work without issue but give incorrect
answers.
One way to identify a logic error is to use RAD Studio to track the value
of the variable with the incorrect result. By seeing how the value
changes with each step of the application, you can usually identify the
point at which the mistake occurs. You will learn more about this
technique in a later chapter.
VALIDATING DATA
Data validation is a technique used by programmers to check (or
validate) the information that users enter before processing it. This
allows programmers to prevent common errors from occurring by
making sure that the information entered is correct before it is used.
The goal of input validation is to prevent users from accidentally or
purposefully entering incorrect data into your program.
If your program automatically generates the data it will use, you can
test the data before using it. You can also improve the algorithm
generating the data to ensure that only the correct types of data are
generated for your program.
New words
step through – to step through
means that you are working through
a program line by line
validate – to try and lessen the
number of errors during the process
of data input in programming
Take note
….
if edtAmount.text = '' then
ShowMessage('Enter a value')
Else
rAmount := StrToFloat(edtAmount.text);
….
Type validation ensures that the data entered is the correct data
type. In your calculator application, you could prevent the user from
entering any values that are not numbers. Alternatively, you could
inform the user that an invalid input was entered if he or she tries to
do a calculation with letters and request them to enter the correct
data.
Length validation ensures that the data entered is the correct
length.
Note
The Length function determines the length of a string.
….
sPassword := edtPassword.text;
if length (sPassword) >= 8 then
….
Else
rAmount := StrToFloat(edtAmount.text);
….
iAge := StrToInt(edtAge.text);
if (iAge > 0) AND (iAge < 120) then
….
Else
ShowMessage('Enter an age in the range 1
to 119');
….
Activity 1.1
1.7.1 What is the difference between syntax, runtime and logic errors?
1.7.2 Give two examples of each of the following errors:
a. Syntax errors
b. Runtime errors
c. Logic errors
UNIT
1.2 Mathematical methods
METHODS
A method is a segment of pre-written programming code that
performs a specific task. Methods are written by the developers of
Delphi. There are two types of methods: functions and procedures.
You have already worked with the data conversion functions IntToStr,
FloatToStr, StringToFloat and StringToInt as well as formatting functions
FloatToStrF and Format. In this chapter, we will discuss mathematical
functions ROUND, TRUNC, FRAC, CEIL, FLOOR, SQR, SQRT and PI
and the procedures INC and DEC.
uses
Windows, Messages, SysUtils, Variants,
Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, ComCtrls,
ExtCtrls, Math;
If you do not know the Unit name of the function or procedure, then do
the following:
Type the name of the function or procedure in the Delphi editor.
Click on the name of the function or procedure you type in the bullet
above.
Press <Ctrl> + <F1> simultaneously.
Delphi Help will provide you with the information of the function or
procedure.
iNum := StrToInt(edtValue.Text);
RANDOMRANGE() FUNCTION
Syntax: RandomRange(Num1,Num2)
The RandomRange function generates a random integer number from
Num1 to one less than Num2.
Example:
iNum := RandomRange(1,7);
ROUND() FUNCTION
The Round function rounds a real number to an integer value.
For example:
rX := 14.5;
iAns := Round(rX);
Steps to complete the rounding:
• Step 1: Establish between which two whole numbers rX lies.
Example 14.5 lies sbetween 14 and 15
• Step 2: Establish whether rX lies exactly halfway between the two
whole numbers. In this case 14.5 lies exactly halfway
between 14 and 15
• Step 3:
If rX lies exactly halfway, then round to the nearest even whole
number. In this case 14.5 will be rounded down to 14
If rX does not lie exactly halfway between the two whole numbers,
then round normally according to mathematical rules to the
nearest whole number
New words
Other Examples:
Activity 1.8
1.8.1 Study the Delphi statement below and then answer the questions that follow:
redDisplay.Lines.Add(IntToStr(Round(rNum));
a. List the function(s) used in the statement.
b. Indicate to which Unit the function(s) belong(s).
1.8.2 Determine the value of iAns in each of the following statements:
a. iAns := Round (8.5);
b. iAns := Round (20.4);
c. iAns := Round (20.7);
d. iAns := Round(21.5);
TRUNC() FUNCTION
The Trunc function truncates (removes or ‘chops off’) the decimal part
of a real number. It returns an integer after the truncation.
Examples:
FRAC() FUNCTION
The Frac function returns the decimal part of a real number. It returns a
real number.
Examples:
CEIL() FUNCTION
The Ceil function rounds a real number up to the highest integer value.
The Ceil Function belongs to the Math Unit and you must add the
Math Unit to the Uses clause before using it, otherwise you will get a
compiler error.
New words
Examples:
FLOOR() FUNCTION
The Floor function rounds a real number down to the lowest integer
value. The Floor Function belongs to the Math Unit.
Examples:
SQR() FUNCTION
The SQR function returns the square of an integer or real number. The
return value is the same type as the number being squared.
Examples:
SQRT() FUNCTION
The SQRT function returns the square root of a number. The result
type is always real. Remember that the square root of a negative
number is undefined.
Examples:
PI
PI is a predefined constant that returns a real number giving a useful
approximation of the value of Pi.
Example:
POWER FUNCTION
Syntax: Power(base,power)
New words
PREDEFINED PROCEDURES
A procedure is also a pre-written subroutine designed to perform a
specific purpose. Unlike a function, a procedure can return no result,
one result or more than one result. A call to a procedure is a
standalone statement whilst a call to a function is always within
another statement. Just like a function, a procedure is only executed
when it is called. We are going to focus on two procedures: INC and
DEC.
INC() PROCEDURE
The INC procedure increments the ordinal type variable passed to it. In
this chapter we will work with ordinal type integers and characters.
…
Line 1: iNum := 6;
Line 2: Inc(iNum);
Line 3: Inc(iNum,5);
…
Explanation of code:
In line 1, the value 6 is assigned to iNum
In line 2, the value stored in iNum is increased by 1 – iNum holds the
value 7.
In line 3, the value stored in iNum is increased by 5 – iNum hold the
value 12
Example of Code:
…
Line 1: cLetter1 := 'A';
Line 2: cLetter2 := 'T';
Line 3: Inc(cLetter1);
Line 4: Inc(cLetter2,2);
Line 5: redDisplay.Lines.Add(cLetter1 +'
'+ cLetter2);
…
Explanation of code:
In line 1, the value 'A' is assigned to cLetter1
In line 2, the value 'T' is assigned to cLetter2
In line 3, the value of cLetter1 is incremented by 1. The ordinal value
of A is incremented by 1. You will learn more about ordinal values
and ASCII values later on in this book. cLetter1 holds the value 'B'
In line 4, the value of cLetter2 is incremented by 2. Again, it’s the
ordinal value of 'T' that is incremented by 2. cLetter2 holds the value
'V'
In line 5, the values B V will be displayed
New words
DEC() PROCEDURE
The DEC procedures decrements an ordinal type variable. The default
is to decrement the ordinal variable by 1 unit, but you can supply an
integer to decrement by a different amount. Example of code using the
Dec procedure:
1.9.1 Open the SquareCubeRoot_p project from the 01 – Square Cube and Square
Root folder and create an OnClick event for the [Calculate] button to do the
following:
• Generate a random number in the range 10 to 20 (inclusive).
• Display the random number in the EditBox.
• For each number from 1 to the random generated number, determine the
square, cube and square root of the number. Tabulate the output. Display
the number, its square,cube and square root with appropriate messages.
Numeric values must be formatted to two decimal places.
• Save and run the project.
Take note
1.9.2 Open the CircleAreaCircum_p project from the 01 – Circle Area and
Circumference folder and create an OnClick event for the Calculate button to
read the radius of a circle and calculate and display the radius, area and
circumference of the circle. The formulae to calculate:
• Area : π r 2
• Circumference : 2π r
Save and run your program.
1.9.3 Open the LearnerAlphabet_p file from the 01 – Learner Alphabet folder. A
letter of the alphabet is allocated in the following manner to each learner:
Learner 1: Z Learner 2: X
Learner 3: V Learner 4: T ….
Do the following:
• Create an OnCreate event to initialise variables for learner number and the
letter of the alphabet that will be assigned to the first learner. Display the
details for the first learner.
• Create an OnClick event for the Generate button to generate and display
the next line of the sequence.
Take note
INSTRUCTIONS
Open the incomplete program in the Question1_1 folder found in the Question 1
folder inside the 01 – Question 1 folder.
Add your name and surname as a comment in the first line of the Question1_1_u.pas
file.
Compile and execute the program. The program currently has no functionality.
SCENARIO
Congratulations! You have been selected to take part in your schools Cricket tour in
New Zealand in the upcoming December holidays. Unfortunately, there are some
costs involved and your parents have stated that you will have to come up with
some of the money yourself. Fortunately, you are an IT student and are able to use
the skills you have learnt in IT to raise some funds.
You have decided to create two applications that will help you to keep track of the
money you will make.
1.1 To earn some money, you have decided to do some painting for your neighbours
and family.
You charge a rate per m2. Open the Delphi project Question1_1_p.dpr, the form
contains the following GUI:
QUESTION 2
In the 01 – Question2 folder, open the project file Question2_p.dpr. Figure 2-1 shows
the GUI design.
Figure 2-1
Due to the growing number of Comicon enthusiasts, each year the number of
participants increases making waiting to just get in considerably time-consuming.
Extreme Comicon wants you to create a program that will make access to the
Comicon by using a pass key and details hassle free. Add code to accomplish this
task.
2.1 Button [Generate Pass Key]
Add code in the button to generate a unique pass key for members to be able to
gain access:
• Two letters of the name starting at the second letter.
• The first four letters of surname
• The letters should all be uppercase
• Any four random digits
• Display the reference number in the TEdit edtPassKey
Example of Input/Output:
Example of Input/Output
QUESTION 3
3.1 Open the Question 3_1 folder found in the Question 3 folder.
Open the file Delimiting_p.dpr
In Grade 11 your syllabus includes the use of text files for storing data long-
term. A common way of storing data of multiple categories is by saving strings
in the text file that are divided by what we call delimiters. These strings would
look something like the following:
As a programmer you always save the name of the book first, then a delimiter
character of your choice and then the price of the book.
NOTE: The delimiter can be any character, but it should be a character that is
highly unlikely to ever be part of any of the strings involved so that the position
of the delimiter character can tell us where to split the strings and then be
removed.
3.1.1 By using the delimiter character given in edtDelimiter, the string in
edtDelimitedString, and your knowledge of string manipulation code the
following in the OnClick event of the btnAdd button:
Split the delimited string into its separate substrings.
Output the name of the book in memBook and the price of the book into
memPrice with the correct currency formatting.
3.1.2 Add code to the OnClick event of btnSummary that will:
Show the total number of books in memBook and the total price of all
the books in memPrice using the correct currency formatting.
Example:
3.2 Open the Question 3_2 folder found in the 01 – Question 3 folder.
Open the project file CoursePass_p.dpr
Cooking for Business is a company that offers short cooking courses for people
who would like to start working in the food industry. This application is going to
be used by participants to check if they have passed the course.
3.2.1 Use the OnExit event of edtName to validate the name that the user
types in by using a loop to check if each character is either an
uppercase letter, a lowercase letter, a space or a hyphen (-). If a
character does not satisfy these criteria, then a relevant message
should show, and focus should go back to edtName.
3.2.2 There are two pass criteria, namely:
• At least 80 for cooking, more than 60 for presentation
• At least 80 for professionalism, above 50 for cooking and
presentation
Complete the IF-statement under the OnClick event of btnCheckPass to
show whether the participants passed or failed.
4.1 A palindrome is a word or phrase that is written exactly the same from front to
back and back to front, for example:
• noon
• civic
• radar
• madam
• able was I ere I saw elba
Your task is to complete the [4.1 Test for palindrome] button code. When the
button is pressed, the text in the text field must be tested. If it is a palindrome, a
popup window must appear with a suitable message, for example:
If it is not a palindrome, it should also show a popup window with a suitable
message. Capital letters and lowercase letters can be ignored. Once a
palindrome is found, the [4.2 Draw] button and side length text field edtSide
must become useable to the user.
4.2 Write the code for the [4.2 Draw] button. When the button is pressed, the value
must be taken from the text field. This value must be the side length of a square
filled with an X O X O X O pattern. Use the memo block for the output. Each odd
row must start with an X and every even row must start with an O. Place spaces
between the characters e.g.
A square with a side length of 5 will look like this
XOXOX
OXOXO
XOXOX
OXOXO
XOXOX
4.3 Write code for the reset button to clear the EditBoxes and MemoBox and to
disable the [4.2 Draw] button and the side length EditBox.
Ensure that your name and surname has been entered as a comment in the
first line of the program file.
Save your program
CHAPTER UNITS
Learning outcomes
INTRODUCTION
In Annexure A we consolidated most work done in Grade 10. Looping
formed an integral part of the Grade 10 curriculum. We focused on the
three loops:
FOR-loop
WHILE-loop
REPEAT-loop
UNIT
2.1 Nested Loops
A nested loop is a loop within a loop, that is, one loop that is placed
inside the body of another loop. We refer to the first loop as the outer
loop and the second loop as the inner loop. We say that the second
loop (inner loop) is nested within the first loop (outer loop).
New words
The outer loop and inner loop can be a combination of the different
loop types. Below is an example of a nested loop that is a
combination of two different loops:
var i, j,iAnswer:Integer;
begin
memDisplay.Lines.Clear;
for I := 1 to 2 do // outer loop
begin
for J := 1 to 3 do //inner loop
begin
iAnswer := I * J;
memDisplay.Lines.Add(IntToStr(I) +' *
'+ IntToStr(J) +' IntToStr(iAnswer));
end;
memDisplay.Lines.Add(' ');
end;
Alternatively, the equivalent code for the flowchart can be written using nested WHILE-
loops. Remember that you can use a FOR-loop or a WHILE-loop for a counter driven
loop.
…
memDisplay.Lines.Clear;
I := 1;
while I <= 2 do
begin
J := 1;
while J <= 3 do
begin
iAnswer := I * J;
memDisplay.Lines.Add(IntToStr(I
) +' * '+ IntToStr(J) +' =
'+ IntToStr(iAnswer));
J := J + 1;
end;
memDisplay.Lines.Add(#13);
I := I + 1;
end;
Activity 2.1
2.1.1 Study the table below and then answer the questions that follow:
a. Write an algorithm to display the multiplication times table for the
numbers 1 to 12 as shown in the table above.
b. Open the MultiplicationTable_p project from the 02 – Multiplication Table
folder. Write code for the [Calculate] button to display the mulitplication
Times Tables for 1 to 12 as shown in the table above.
2.1.2 Open the MultiplicationTableFormat_p project from the 02 – Multiplication
Table Format folder. Write code for the [Calculate] button to display the table
as shown below:
Note:
A number in the first row multiplied by a number in the first column will yield the
product of the two numbers.
To find the product of 4 × 5:
place a finger on the number 4 in the first row
place another finger on the number 5 in the first column
move the finger in the first row to the right and the finger in the first column
down
where both your fingers meet is the product of the two numbers. In this case 20.
Remember that multiplication is commutative, that is, a × b can be written as b ×
a. Therefore you could have started by multiplying the number 4 in the first column
with the number 5 in the first row.
UNIT
2.2 Using nested loops
https://www.youtube.com/watch?
v=LpuPe81bc2w
https://qrs.ly/6dab1zo
Note:
Any number raised to the power zero (No) is equal to 1.
You must follow the BODMAS rules.
[begin code]
procedure TForm1.FormActivate(Sender:
TObject);
begin
edtNumber.SetFocus;
end;
[end code]
Activity 2.2
Refer to the algorithm to convert a binary number into decimal number above .
2.2.1 Draw a trace table for the algorithm using an input value 1012.
2.2.2 Open the BinaryToDecimal_p project in the 02 – Binary to Decimal Folder.
• Create an OnActivate event on the form to set the cursor to focus on the
EditBox.
• Create an OnClick event for the [Convert To Decimal] button to convert a
binary number to a decimal number. Use the algorithm to convert a binary
number to a decimal number.
• Run and execute the program.
• Save the program.
Read number
BinNum = ' '
Repeat
Remainder = integer (remainder of number/2)
BinNum = string value(remainder) +
BinNum
Number = integer (division of Number/2)
Until number = 0
Display BinNum
Activity 2.3
• Change the property of the MemoBox so that you can scroll through the
display if all the data cannot be seen.
2.3.2 The hexadecimal number system has 16 digits: 0–9, A–F.
You will remember from Grade 10 that the Hexadecimal numbers A–F
represent the decimal numbers 10 – 15 respectively. Open the
ConvertToHex_p project in 02 – Hexidecimal to Decimal Vice Versa folder and
do the following:
• Create an OnClick event for the [Convert to Dec] button to read in a
hexadecimal number and convert the number to decimal. Display the
Hexadecimal number and the Decimal number
https://www.khanacademy.org/math/
algebra-home/alg-intro-to-
algebra/algebra-alternate-number-
bases/v/decimal-to-hexadecimal
NUMBER CIPHER
In a number cipher each character in a message is converted to an
encrypted number in the following manner:
All the characters that are going to be used to create messages are
identified and a character list is compiled. Example:
ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789.,!?:–+=”( )[ ]
Note: a space character appears after the character ‘Z’ in the
character list.
A message is created using the character list and all letter characters
are converted to uppercase.
Each character in the character list has a numerical position in the
list:
ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789.,!?:–+=”( )[ ]
A is in position 1
B is in position 2
C is in position 3
…
The numerical position of each character in the message in the
character list is found. Example: the numerical position of each
character in the message Stop the war is:
19 20 15 16 27 20 8 5 27 23 1 18
The numerical positions of the characters is decreased by a fixed
number. For example, let’s decrease the numerical position of the
characters by 5. The encrypted message is then:
14 15 10 11 22 15 3 0 22 18 –4 13
The encrypted characters are separated by space.
sOutput := '';
sCharacterList :=
'ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789.,!?:-+="()[]';
Read the message that you want encrypted from the EditBox and covert all letter
characters to uppercase:
sText := UpperCase(edtText.Text);
Check if the [Number Cipher radio] button is selected. If the [Number Cipher] radio
button is selected, then:
Extract each character from the message and check for its numerical position in
the character list sCharacterList.
Store the numerical position in iNumber
Add the numerical position and a space to variable sOutput
New words
if rgpCipher.ItemIndex = 0 then
begin
for i := 1 to Length(sText) do
begin
sChar := sText[i];
for j := 1 to Length(sCharacterList) do
if sChar = sCharacterList[j] then
iNumber := j;
iNumber:= iNumber-5;
sOutput := sOutput + IntToStr(iNumber) +
' ';
end;
end;
Display the message string sText and the encrypted message sOutput
Activity 2.4
2.4.1 Open the Cryptographer_p project in the 02 – Cryptographer folder and add
code to the OnClick event for the [Encrypt] Button to do the following:
• If the radio button Caesar Cipher is selected then:
Set a new string variable to null.
Read the message that you want to decrypt in the appropriate
EditBox.
Isolate the first number in the encrypted message and convert the
number to an integer and add 5 to the number.
Find the character that is stored in the character list in the integer
position calculate in bullet 2. Add the found character to the string
created in bullet.
Continue with bullets 2 and 3 until the last number in the encrypted
message is decrypted to the correct character.
• Save and run your project.
2.4.2 A composite number is a number that has 3 or more factors.
For example: 4 is a composite number because it has three factors: 1 2 4
Open the CompositeNumber_p project in the 02 – Composite Number Folder.
Write code for the OnClick event for the [Find] button to display all the
composite numbers that are less than 30.
UNIT
2.3 Creating shapes using nested loops
You can create simple geometrical shapes using special characters
such as ‘*’ or digits.
Example 2.1 Create the shape below using the special character ‘*’
We know that there are six rows and each row has 6 *s. The code to draw this
shape:
******
******
******
******
******
******
Line 1: for i := 1 to 6 do
Line 2: begin
Line 3: sLine := ’’;
Line 4: for j := 1 to 6 do
Line 5: sLine := sLine +'*';
Line 6: memDisplay.Lines.Add(sLine);
Line 7: end;
Note:
Line 1: The outer i-loop will run six times because there are six rows.
Line 3: String sLine is set to null for each row.
Line 4-5: In each row, 6 *’s must be joined together.
Line 6: Display the string sLine before moving to the next row.
We know that there are six rows and each row has 6 *s. The code to draw this
shape:
**
***
****
*****
Line 1: for i := 1 to 5 do
Line 2: begin
Line 3: sLine := '';
Line 4: for j := 1 to i do
Line 5: sLine := sLine +'*';
Line 6: memDisplay.Lines.Add(sLine);
Line 7: end;
Note:
Line 1: The outer i-loop runs from 1 to 5 because we have five rows.
Line 3: String sLine for each row is set to null.
Line 4 & 5: Each row does not display the same number of *s. Therefore the
inner j-loop cannot run to a fixed constant value. We see from the table below
that there is a relationship between the row number and the number of *s that
will be displayed. Hence the inner loop runs from 1 to i.
Line 6: Display the string sLine before moving to the next row.
If we want to display the same shape formatted as follows:
*
**
***
****
*****
with
memDisplay.Lines.Add(Format('%10s',
[sLine]));
**
***
****
*****
******
*****
****
***
**
for i := 1 to 6 do
begin
sLine := ’’;
for j := 1 to i do
sLine := sLine +'*';
memDisplay.Lines.Add(sLine);
end;
for i := 5 downto 1 do
begin
sLine := '';
for j := 1 to i do
sLine := sLine +'*';
memDisplay.Lines.Add(sLine);
end;
Activity 2.5
2.5.1 Study the code segment below and determine the output:
for i := 1 to 5 do
begin
sLine := '';
for j := 1 to i do
sLine := sline + IntToStr(i) ;
memDisplay.Lines.Add(sLine);
end;
2.5.2 Open the Shapes_p project in the 02 – Shapes Folder and do the following:
Set the font property of the MemoBox to Courier New.
Create an OnClick event for the [Pattern 1] button to create and display the
pattern alongside. The stars are separated by spaces. The memo
component must be cleared before displaying the pattern.
Create an OnClick event for the [Pattern 2] button to create and display the
pattern below.
The memo component must be cleared before displaying the pattern.
Create an OnClick event for the [Pattern 3] button to create and display the
pattern below. The memo component must be cleared before displaying the
pattern.
QUESTION 1
1.1 Assume that the value for variable iSize is 5. Determine the output that will be
produced by the following code segment:
for i := 1 to iSize do
begin
sLine := '';
for j := iSize downto i do
sLine := sLine +'*';
memDisplay.Lines.Add(sLine);
end;
QUESTION 2
2.1 Open the ConPatterns_p project in the 02 – ConShapes Folder and do the
following:
2.1.1 Code the OnClick event for the [Pattern 1] button to test your code for
question 1.2 above.
2.1.2 Code the OnClick event for the [Pattern 2] button to display the stars as shown
below. The stars are separated by spaces.
******
*****
******
*****
******
2.1.3 Code the OnClick event for the [Pattern 3] button to display the stars as shown
below. The stars are separated by spaces.
*
**
***
****
*****
******
*****
****
***
**
*
QUESTION 3
3.1 A number is a perfect number if its factors (excluding the number itself) sums
up to the number.
Example: The factors of 6 are: 1 2 3 6.
1 + 2 + 3 = 6. Therefore 6 is a perfect number.
Open the PerfectNumber_p project in the 02 – Perfect Numbers Folder. Create
an OnClick event for the [Calculate] button to calculate the first four perfect
numbers.
Sample Run:
3.2 Open the SecretMessage_p project in the 02 – Secret message folder. The
following interface will display when the program is run:
QUESTION 4
A multiplication tester program is designed to test the product of two numbers. The
user is prompted for the number of questions the user would like to work through. For
each question, two random numbers in the range 1 to 10 (inclusive) are generated
and the user is asked to supply the product. If correct, four points are awarded.
If incorrect, the user is given another chance; if correct this time, only two points are
awarded. If the user fails on the second chance, the program provides the answer and
no points are awarded.
Open the MultiplicationTester_p project in the 02 – Multiplication Tester Folder and
create an OnClick event for the [Tester] button to do the following:
Read the number of questions from the EditBox edtNumQuestions.
Generate two numbers iNum1 and iNum2 and display the numbers in the
edtNum1 and edtNum2 EditBoxes respectively.
Prompt the user for the correct answers using an Input box.
Display whether the answer is correct or incorrect using a ShowMessage box.
Display the Points earned in the memDisplay box.
Example output for Question 4
CHAPTER UNITS
Learning outcomes
INTRODUCTION
In many applications, large amounts of data need to be stored and
accessed randomly. While it might be possible to create a variable for
each data item that needs to be stored (such as your website’s
usernames and passwords), this could cause a number of issues.
These include:
New words
So, instead of creating separate variables for each item, this chapter
will teach you how to create an array that can store multiple values in
the same structure.
UNIT
3.1 Arrays
DELPHI ARRAYS
https://www.youtube.com/watch?
v=a7V8P4zE0ss
TRO –SHORT LINK
A one-dimensional array contains only one row for storing data. The
elements in an array are ordered. The ordering property implies that
the first, second, …, last element can be identified or referenced.
Take note
DECLARATION OF AN ARRAY
Just like a variable, an array must be declared before it is used. Here is
an example of the declaration of an array:
arrName: array[StartIndex..LastIndex] of
Type;
Remember!
Var
arrNames:array[1..6] of String =
('Tom','Jerry','Mickey', 'Mouse',
'Daisy','Donald');
arrPoints:array[1..10] of integer =
(56,45,78,36,45,62,25,78,96,25);
POPULATING AN ARRAY
ASSIGNING VALUES TO AN ARRAY IN A SPECIFIC POSITION
The statements below demonstrate how elements in an array are
assigned values:
arrNames[1] := 'Arhaan';
arrValue[7] := Sqr(5) ;
arrNumPeople[iCount] := 6;
arrMaxRainfall[i] := arrMaxRainFall[i + 1];
arrMark[4] := StrToInt(edtMark.text);
for i := 1 to 5 do
arrScores[i]:=StrToInt(InputBox('Scores','
Enter score',''));
By using the InputBox with an array and a FOR-loop, you can ask the
user to enter a value for each element of the array.
memDisplay(IntToStr(arrScore[1]));
memDisplay(IntToStr(arrScore[2]));
memDisplay(IntToStr(arrScore[3]));
memDisplay(IntToStr(arrScore[4]));
memDisplay(IntToStr(arrScore[5]));
Method 1 is fine as long as you have only a few elements in the array.
However, what happens when you have 100 elements. Using this
program will become cumbersome because you will have 100 output
statements. Instead, you can use a loop to display a large amount of
elements.
For i := 1 to 5 do
memDisplay.Lines.Add(IntToStr(arrScores[i]
);
Take note
Activity 3.1
3.1.1 Pen and paper activity. Write down code that will do the following:
• Declare an array called arrName that can store three string values.
• Store the names of a friend, a family member and a pet in the array (in
that order).
• Use the ShowMessage method to display the following names:
a. Pet’s name
b. Family member’s name
3.1.2 Pen and paper activity. Write down code that will do the following:
Declare the following four array variables.
Assign the name of South Africa’s nine provinces into an array arrProvinces.
Assign the value FALSE to every second value of array arrCardInDeck.
Create a FOR-loop that assigns random numbers between 1 and 20
(inclusive) to array arrNumbers. Array arrNumbers is type integer containing
50 elements.
3.1.3 Open the TestMarks_p project in the 03 – Test Marks Folder. The project is
supposed to display the marks of the learners which are stored in the array.
However, there are errors in the program. Correct the errors in the program so
that it produces the correct output as shown on the right hand side.
3.1.4 Open the FamilyTree_p project in the 03 – Family Tree Folder and do the
following:
a. Declare a non-local (global) array called arrNames since the values in this
array will be accessed by each of the buttons.
b. Create an OnCreate event for the form to assign the name of a family
member to each of the elements in the array:
Father: John
Mother: Mary
Brother: Peter
Sister: Sarah
c. Create an OnClick event for [Father] button to display the name of the
father from the array in a ShowMessage box and also added to the
ListBox lstFamily.
d. Create OnClick events for the [Mother], [Brother] and [Sister] buttons to
display the relevant names from the array in a ShowMessage dialogue
box and in the ListBox lstFamily.
e. Save and test your application. You should now be able to display the
names of your different family members by clicking on their buttons.
3.1.5 The names of games are stored in an array. Open the GameNames_p project
in the 03 – Game Names Folder and do the following:
a. Write code for the [Display] button to display the names of the games.
b. Write code for the [New] button to add the text ‘New’ to every second
element of the array starting from the first element.
c. Write code for the [Select] button to randomly select a game and display
the name of the game using a DialogBox.
d. Write code for the [Reverse] button to reverse the characters of each
element in the array. Display the array.
...
{1} iMax := arrMarks[1];
{2} iPosition := 1;
{3} for i := 2 to 5 do
{4} begin
{5} if arrMarks[i] > iMax then
{6} begin
{7} iMax := arrMarks[i];
{8} iPosition := i;
{9} end;
{10} end;
{11} memDisplay.Lines.Add('The highest
mark: '+ IntToStr(iMax) +' at
position '+ IntToStr(iPosition));
…
Assume that arrMarks contains the following values: 45, 90, 12, 40
and 72. Let’s trace through the code segment above.
Activity 3.2
The marks are stored in array arrMarks. Open the MathsCalc_p project in the 03 –
Math Calc Folder and write code for the following buttons:
[Display] button to display the elements of the array.
[Average] button to find and display the sum and average of the marks.
[Product] button to find and display the product of the elements.
[Range] button to find and display the highest and lowest mark and the position of
the highest and lowest mark in the array and the range of the marks. The range is
the difference between the highest and lowest mark.
[Percentage] button to convert each mark to a percentage. The marks are out of 60
marks. Display the original mark and the rounded percentage calculated to zero
decimal places.
Algorithm
Count ← 0
For loop i ← 1 to length of array
If array[i] matches criteria
Count ← Count + 1
End FOR-loop
Activity 3.3
3.3.1 An array called arrNumbers has been declared. Open the Counters_p project
in the 03 – Counters Folder and write code for the following:
a. [Even/Odd] button: Determine and display the number of even and odd
numbers.
b. [Negative/Positive] button: Determine and display the number of negative
and positive numbers. Remember that zero is neither negative nor
positive.
c. [Composite] button: Determine how many numbers are composite. A
composite number is a number that has more than two factors.
All outputs must be accompanied by suitable messages.
3.3.2 An array called arrNames has been declared. Open the ClassList_p project in
the 03 – Class List Folder and write code for the [Find by letter] button to
prompt the user to input a letter of the alphabet (use an InputBox). Count how
many names in the given array arrNames begin with the letter provided by the
user. Display the count value using a dialogue box.
USING AN ARRAY AS A COUNTER
You can also use an array as a counter.
Example 3.1
Your school plans a market day to raise funds. The schools will have 10 stalls
selling different categories of items. They need to keep track of the popularity of
each stall for future planning.
Since we are counting the popularity of 10 stalls, we would need to use 10 counter
variables. This will become too cumbersome. A better solution would be to use an
array as a counter where each stall is numbered from 1 to 10 and associated with
each index position of an element in an array.
You need to set each element in the counter array to zero as shown below:
As customers visit a stall, the corresponding element matching the stall number is
updated. If a customer visited stall number 3, the element at index position 3 is
incremented by one.
To determine the most popular stall, you need to find the stall with the highest
number of customers.
Activity 3.4
3.4.1 Using the school market day example, open the PopularStall_p project in the
03 – Popular Stall Folder and write code for the following:
Declare an array arrPopCount.
[Update Visits] button: Every time this button is clicked, a random number in
the in the range 1 to 10 is generated. This number represents the stall
number that a customer has visited. The randomly generated number will
be displayed on a label lblStallNumber. Keep count of the stalls visited using
the array arrPopCount. Display the stalls visited as each stall is visited.
[Determine Most Popular] button: Determine and display the most popular
stall.
INSERTING AND DELETING ELEMENTS IN AN ARRAY
INSERTING AN ELEMENT IN AN ARRAY
You can insert an element into a specific position in an array.
Example 3.2
Let’s insert a value, 56, at the 4th position in the array below:
Remember, the number of elements in the array increases by one so the upper
bound of the array must be increased by one.
All the elements from the 4th position must move to the right starting with moving
the last element first:
arrHighScores[11] := arrHighScores[10];
arrHighScores[10] := arrHighScores[9];
…
arrHighScores[5] := arrHighScores[4];
The code for the movement of the elements:
for i := 10 downto 4 do
arrHighScores[i + 1] :=
arrHighScores[i];
Alternatively:
for i := 11 downto 5 do
arrHighScores[i] := arrHighScores[i-
1];
You cannot start the movement of elements from the 4th element first, because it
will overwrite the values on the right-hand side.
Example 3.3
Let’s delete the value 18 from the 3rd position in the array below:
All the elements from the 4th position must move to the left starting with the
movement of the element at the 4th position first:
arrHighScores[3] := arrHighScores[4];
arrHighScores[4] := arrHighScores[5];
…
arrHighScores[9] := arrHighScores[10];
The code for the movement of the elements:
for i := 3 to 9 do
arrHighScores[i] := arrHighScores[i +
1];
Alternatively:
for i := 4 to 10 do
arrHighScores[i-1] :=
arrHighScores[i];
Although we moved the elements to the left, the last element still exists.
When we display, we must only display the first nine elements.
Example 3.4
arrTemp[1] := arrNames[1];
iCounter := 1;
//Loop through each element in arrNames. Loop starts from 2 because the first
//element is catered for
for i := 2 to 19 do
begin
bFlag := true;
//Initialise counter value for inner loop to loop through the elements
//of arrTemp.
j := 1;
//The loop terminates either when a match is found or when the last
//element in arrTemp is reached
//If no match is found then increment the counter for arrTemp and
//store the value of the element in arrNames in the new counter
//position in arrTemp
if bFlag then
begin
Inc(iCounter);
arrTemp[iCounter] := arrNames[i];
end;
end;
for i := 1 to iCounter do
arrNames[i] := arrTemp[i];
Activity 3.5
3.5.2 Write code for the [Insert Shift] button that will:
Prompt the user to input the name of the staff member using an Input Box.
Insert the new shift at position 5 in the array.
Increment the value of iCount by 1.
3.5.3 Write code for the [Delete Shift] button that will:
Prompt the user to input the position they wish to delete using an Input Box.
Remove the specified value from the array.
Decrease the value iCount by 1.
3.5.5 At the end of every week, all staff shifts are reset to a value of 1. This means
that each staff member’s name should appear in the array only once.
Write code for the [Reset Staff Shifts] button that will:
Iterate through the array arrStaff and remove all duplicates.
Modify the value of iCount to reflect the number of items remaining in the
array after the duplicates have been removed.
UNIT
3.2 Searching and sorting arrays
SEARCHING ARRAYS
When working with large amounts of data, it is impossible to know the
exact location of each element. So, if you want to search and locate
specific elements in an array, you could use two methods:
linear search
binary search.
LINEAR SEARCH
When using a linear search, you can loop through the elements of the
array to find the value that you are looking for. The loop will terminate
when the:
value is found
last index position is reached and the value is not found.
i := 1;
iPos := 0;
bFlag := false;
sSearch := Input('Name','Enter name','');
while (i <= 10) and (bFlag = false) do
begin
inc(i);
if arrNames[i] = sSearch then
begin
bFlag := true;
iPos := i;
end;
end;
if bFlag = true then
memDisplay.Lines.Add('Found: ' +
arrNames[iPos])
else
memDisplay.Lines.Add(sSearch + ' not
found’);
New words
…
Const
arrNames:array[1..10] of string =
('Jack','Sanele','Alonso',
'Arhaan','Zinhle','Brian','Paul','Sarah','Akira
','Zainab');
…
sSearch := Input('Name','Enter name','');
bFlag := false;
for i := 1 to length(arrNames) do
begin
if sSearch = arrNames[i] then
begin
bFlag := true;
memDisplay.Lines.Add(arrNames[i]);
end;
end;
if bFlag = false then
memDisplay.Lines.Add(‘Name not found’);
Take note
SORTING ARRAYS
Arrays can be sorted in ascending or descending order. This year you
will learn about two ways in which arrays can be sorted:
bubble sort
selection sort.
New words
BUBBLE SORT
The bubble sort compares adjacent elements. To sort elements in
descending order, compare two adjacent elements. If the first element
is less than the second element then swap the elements.
Pass 1 :
Because this is a descending sort, the smallest element “bubbles” to
the last position in the array.
Pass 2 :
Pass 3 :
Here is the code for a bubble sort using two nested FOR-loops:
SELECTION SORT
The selection sort is one of the simplest sorting algorithms. Although it
is an easy sort to program, it is one of the least efficient. The algorithm
offers no way to end the sort early, even if it begins with an already
sorted list. It works by selecting the element that should go in each
array position either in ascending or descending order sequence.
Example:
At the end of the comparisons for index position2, the second smallest
element is in index position2.
Step 3: Continue in this way for all the locations of the array. In the
last step only one comparison takes place. The second last element
arr[4] will be compared to the last element arr[5].
The selection sort will be implemented using nested loops.
An element has to be kept constant until it is compared to every
element to its right. The index position of the outer loop (variable i) is
used to keep an element constant.
The inner loop (variable j) caters for the indices of the elements to the
right of the constant element
The comparisons take place as follows based on the index positions:
Here is the code for a selection sort:
…
// declare and initialize array
elements
int [] arr = (5,9,2,8,1);
int temp;
// outer loop holds index of element
being compared
for i := 1 to arr.length-1 do
// inner loop hold index of
elements being compared to
for j := i+1 to arr.length do
// checks if the element is > the
element being compared to
if (arr[i]>arr[j])
Begin
// if true, swop elements
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
End;
Activity 3.6
3.6.1 Open SortApp_p in the 03 – Sort Application folder. The following interface
has been provided:
The code for the [Generate Elements] button has been provided that populates
and displays the array with the number of elements specified in the SpinEdit.
Note that the number of items in the array is stored in the global variable
iItems.
3.6.2 Write code for the [Selection Sort Descending] button that will sort the array in
Descending Order using the Selection Sort algorithm. Display the array in the
Memo Box memSorted.
3.6.3 Write code for the [Bubble Sort Ascending] button that will sort the array in
Ascending Order using the Bubble Sort algorithm. Display the array in the
Memo Box memSorted.
BINARY SEARCH
Whilst the linear search is effective with smaller arrays, larger arrays
would result in very poor efficiency in terms of the number of tests that
need to be made to search for a specific value. The search would start
at the beginning of the array and terminate only once the specific value
is found. So, if an array has 10 000 elements and the specific value is
found in the second last position, the linear search will run up to 9 999
tests for the specific value. In the worst case scenario, all elements will
be tested if the specific value is not found in the array. This means that
if the array has 10 000 elements, then 10 000 tests will be made.
Let’s assume that we want to search for the value 222 in an array. The
binary search works as follows:
New words
Step 4: Go back to step 2 until the search value is found or the start
index value is greater than end index value.
Look at the pseudocode below for this search:
Activity 3.7
3.7.1 Open the BinarySearch_p project and write code for the following:
[Generate] button: to generate 20 values in the range 10 to 99 and store
the values in an array.
[Sort] button: Sort the array in descending order.
[Display] button: Display the elements in the array.
[Search] button: Prompt the user to enter a number in the range 10 to 99.
Determine whether the number is found in the array using the binary
search. If the number is found, then display the number and its position in
the array. If the number is not found in the array, an appropriate message
must be displayed.
UNIT
3.3 Parallel arrays
Remember that an array can only store elements of the same data
type. However, if you want to store related information of different data
types, you need different arrays. For example, if you want to store the
names and marks of learners, then you need to store the names in one
array and the marks in another array. But, the names and marks are
related. Each element in one array is linked to an element in the
second array by its index position. For example, in the arrays below,
Peter’s name is stored in arrNames[3] and his mark is stored in
arrMarks[3].
…
for i := 1 to 4 do
begin
for j := i + 1 to 5 do
begin
if arrMarks[i] < arrMarks[j] then
begin
iTemp := arrMarks[i];
arrMarks[i] := arrMarks[j];
arrMarks[j] := iTemp;
sTemp := arrNames[i];
arrNames[i] := arrNames[j];
arrNames[j] := sTemp;
end;
end;
end;
…
New words
Look at the code below that shows how elements in parallel arrays can
be searched:
Activity 3.8
Take note
1.1 Determine the total votes cast by calculating the sum of the values in arrVotes.
Store the sum in a global variable called iTotal.
1.2 Use iTotal (from 1.1) to determine the number of seats each party will get. The
number of seats depends on the ratio of votes that a particular party received.
Store the number of seats for each party in arrSeats. (Round your answer to an
Integer value).
1.3 Write code to determine which party received the highest number of votes.
Display the Party name (from arrCandidates) and the number of votes (from
arrVotes).
1.4 Create a sorting algorithm and flowchart that can be used to sort arrVotes in
descending order.
1.5 Create code that can be used to sort all the arrays based on the number of
seats in Parliament; arranged in ascending order.
QUESTION 2
For this application, open the project saved in the 03 – Question 2 – Password
Strength Folder. Once done, save the project in the same folder. For this question, an
array called arrPasswords has been declared and populated in the [Generate 20
Random Passwords] button.
2.1 Write code for the [Test Password] button that reads the password from the
EditBox edtPassword and determines whether the password is strong or weak.
A strong password needs to meet all the following criteria:
• The length of the password is a minimum of 6 characters.
• The password contains at least one digit.
• The password contains at least one letter.
• The password contains at least one of the following special characters: * , #
, ? , $.
Otherwise, the password is considered to be weak.
2.2 Add the password, as well as the strength of the password, to the ListBoxes as
shown below.
2.3 When the [Check All] button is pressed, use a FOR-loop to check the strength of
all the passwords in the array.
2.4 Record the strength of all passwords in a parallel array named arrStrength.
2.5 Display all the passwords, as well as the strength of the passwords, as shown
above.
QUESTION 3
Open project BoxOffice_p in the 03 – Question 3 – Box Office Folder that provides the
following interface:
Two parallel arrays have been declared and initialised:
arrMovies – an array of type String containing the names of movies.
arrTickets – a parallel array of type Integer containing the number of tickets sold for
each movie in arrMovies.
The variable iItems tracks the number of items in the Array.
3.1 When the [Hit or Miss] button is pressed: Determine and display which movie
has sold the greatest number of tickets. At the same time, determine and
display which movie has sold the least number of tickets.
3.2 When the [Average] button is pressed: Determine and display the average ticket
sales across all the movies being shown.
3.3 A businessman has sponsored 100 tickets per movie to a local school. Write
code for the [Block Adjust] button, which will increase the ticket sales of all
movies by 100.
3.4 Movies have a limited run on circuit. This means that eventually, it is removed
from cinema listings and is released to home video or streaming services. Write
code for the [Remove] button which will prompt the user to input the name of a
movie. Locate the movie in the movies array and remove its entries from both
arrays.
CHAPTER UNITS
Learning outcomes
INTRODUCTION
In Grade 10, you learned how to manipulate strings by using FOR-
loops to access each character in the string. By doing this, you were
able to:
find a character in the string
replace a character in a string
delete a character from a string
insert a character into a string.
In this chapter, you will learn about built-in string methods that allow
you to do the same thing without having to use a FOR-loop. You will
also learn how to use these methods to manipulate individual words
and phrases from strings. We will also focus on the use of Date
methods.
UNIT
4.1 Built-in string methods
Take note
New words
CONCAT() FUNCTION
The CONCAT–function concatenates (joins) strings (String1, String2
...) together into one result string. It is equivalent to the + operator.
Thus far you have been using the + operator to join strings, for
example, sSentence:=sSentence+sWord
Syntax: CONCAT(Sstring1,sString2, …)
sStringl: refers to the first string to be joined.
sString2: refers to the second string to be joined.
…: indicates more strings can be joined.
COPY() FUNCTION
The COPY–function returns a copy of a certain number of characters
from a string. The result is a string that is part of the original string,
which we refer to as a substring.
Example:
Example:
We can have more than one method with the same name. This is
called method–overloading.
4.1.1 Study the declaration below and determine the output in the table provided:
POS() FUNCTION
The Pos function returns the start position of one string within another
string as an integer. For example, the start position of ‘mark’ in ‘fish
market’ is 6.
New words
Note:
sSubstring can be a character or a string.
Pos looks for an exact string and is case sensitive.
Pos returns the start position of the substring sSubstring in the string
sString.
Examples:
iPos := Pos(‘at’,’Leave at 10’) will result in iPos := 7.
iPos: = Pos(‘v’,’Leave at 10’) will result in iPos := 4.
If there are many occurrences of the substring sSubstring in the
string sString, then the start position of the first occurrence of the
substring is returned.
Example:
iPos := Pos('a','Leave at 10') will result in
iPos := 3
Example:
4.2.1 Study the declaration below and determine the value of iAns. Complete the
table below.
4.2.2 Study the Delphi code segment below and answer the questions that follow:
Assume that the string ‘Ariana Grande’ is read for the sFullNames variable
using the edtFullNames EditBox:
a. Write a Delphi statement that will extract the first name from sFullNames
and store the name in sName. This code should work for any full name
read.
b. Write a Delphi statement that will extract the surname from sFullName
and store the surname in sSurname. This code should work for any full
name read.
SETLENGTH() PROCEDURE
The SETLENGTH procedure changes the size of a string.
New words
When changing the size of a string sString, the new size iNewLength
may be smaller, the same size or larger than the existing string length.
In all cases, the size is in characters, and a new string is created
regardless.
Note:
If the new size of the string is smaller than the original size of the
string, the string gets truncated, that means that if the string
contains 15 characters and the new size is 10, then the last 5
characters are ‘chopped’ off.
Example:
After the statements above are executed, the value of sString will be:
‘Change is the’
If the new size of the string is larger than the original length of the
string, then space for extra characters are added but these extra
characters are not initialised. This can create odd effects.
Example:
sString := 'Plenty';
setLength(sString, 15)
memDisplay.Lines.Add(sString);
sStr := 'Plenty';
setLength(sStr, 10);
memDisplay.Lines.Add(sStr);
After the statements above are executed, the results returned could
be:
PlentyFormat
Plentyion
Activity 4.3
a. Write code to initialise the extra places created in line 2 with a ‘-‘
character.
b. Why is this initialisation of the extra space so important?
INSERT() PROCEDURE
The Insert procedure inserts one string into another string. Unlike
functions, the INSERT procedure changes the string, that is, after the
procedure is called, the previous value of the string is permanently
changed.
New words
Insert – to insert one string into
another string
Note:
Any characters to the right of the insertion position will be moved to
the right.
The length of the string will increase by the number of characters
inserted.
Example:
…
sPhrase := 'IT is my favorite subject';
Insert('really ', sPhrase, 7);
Insert('really ', sPhrase, 6);
Insert('really ',' IT is my favorite
subject', 6);
…
New words
Delete – to delete a number of
characters from a string starting from
a start position
Note:
Any characters to the right of the deleted characters will be moved
to the left.
The length of the string will decrease by the number of characters
deleted.
Example:
…
sPhrase := 'IT is not my most favourite
subject'
Delete(sPhrase, 7, 4);
Delete(sPhrase, 10, 5);
Delete(sPhrase, 1, 100);
Delete(‘I love IT’, 1, 1);
…
The outcome after the Delete statements are executed one after the
other:
Activity 4.5
Given: sValue:=’Johannesburg’
Write down independent Delphi statements to do the following:
4.5.1 Determine the length of sValue.
4.5.2 Remove the string ‘hannes’ from sValue.
4.5.3 Find the position of ‘ann’ in sValue.
4.5.4 Return characters 3 to 5 from sValue.
4.5.5 Insert the string ‘hannes’ after the letters ‘Jo’ in sValue.
New words
Open the StringProblems_p project in the 04 – String Problems Folder. You should
see the following user interface when you run the project.
Create OnClick events for buttons: Question 1, Question 2, Question 3, Question 4
and Question 5 as follows:
Question 1 button
Determines whether the input text contains a comma or not. Displays an
appropriate message in the MemoBox indicating whether the comma was found or
not. If the comma was found, display the position of the comma in the input string.
sInput := edtInput.Text;
iPos := Pos(',', sInput);
if iPos > 0 then
memOutput.Text := 'Comma found at position '
+ IntToStr(iPos)
else
memOutput.Text := 'Comma not found';
Notes:
The POS function is used to determine the position of the comma in the input
string.
If the value returned by the POS function in iPos is equal to 0, then a comma
is not found in the input string; otherwise the comma is found in position iPos.
Question 2 button
Deletes any characters in the input text up to (and including) the first space. If there
is no space in the text, no characters are deleted. Display the changed input text in
the MemoBox.
sInput := edtInput.Text;
iPos := Pos(' ', sInput);
Delete(sInput, 1, iPos);
memOutput.Text := sInput;
Notes:
Pos function is used to determine the position of the first space.
All characters can then be deleted from the start of the text to the position of
the space.
If no space is found, Pos will return a value of 0 and no characters will be
deleted.
Question 3 button
Move the first three characters of the input text to the end of the input text. Display
the changed input text in the MemoBox.
sInput := edtInput.Text;
sCharacters := Copy(sInput, 1, 3);
Delete(sInput, 1, 3);
sInput := sInput + sCharacters;
memOutput.Text := sInput;
Notes:
The first three characters are copied to a new string sCharacters before being
deleted from the input string sInput.
After the first three characters are deleted from sInput, they can be added to
the end of sInput.
sInput is displayed in the memo component.
Question 4 button
Deletes all copies of the lowercase character ‘s’ from the input text. Display the
changed input string in the Memo box.
sInput := edtInput.Text;
iPos := Pos('s', sInput);
while iPos <> 0 do
begin
Delete(sInput, iPos, 1);
iPos := Pos('s', sInput);
end;
memOutput.Text := sInput;
Notes:
The position of the first ‘s’ is determined using the POS function and stored in
iPos.
While iPos <> 0, delete the ‘s’ from sInput and find the next ‘s’ in sInput.
Continue this process while iPos <> 0.
By using a WHILE-DO-loop, you can continue searching through your input text
sInput and deleting all ‘s’ characters until no ‘s’ characters are found.
Question 5 button
Inserts a space after every character of the text. Display the changed input string in
the MemoBox.
sInput := edtInput.Text;
i := 1;
while i <= Length(sInput) do
begin
i := i + 1;
Insert(' ', sInput, i);
i := i + 1;
end;
memOutput.Text := sInput;
Notes:
You can use a WHILE-loop with the Insert command to add a space after each
character.
With this code, you need to make sure that your loop does not add a space after
the space it previously added.
This will cause your program to go into an infinite loop where each iteration of
the loop simply adds another space after your previously added spaces.
Therefore, in the code above, the value of ‘ I’ is incremented twice. The first time
it increases it selects the next character, while the second increase moves ‘ I’
past the newly added space.
Save and run your project.
Activity 4.6
4.6.1 To make messages more interesting, the word ‘flapping’ must be added
between the first two words of a message. Open the FlappingWord_p project
in 04 – Flapping Word Folder and do the following:
Create an OnClick event for the [Send Flapping Message] button to read a
message from the EditBox
Add the word ‘flapping’ in between the first two words of a message.
Display the message in the MemoBox.
Save and run the project.
4.6.2 Coming up with interesting, new compliments in a relationship can be
challenging, especially after you have been in a relationship for a long time. To
solve this problem, you have decided to create the Love Letters application
that will randomly generate new compliments whenever you click on a button.
Open the LoveLetters_p project in the 04 – Love Letters Folder.
When you click on the [Generate compliment] button, the application should do
the following:
Store several greetings, pet names and descriptions in three arrays. These
arrays have already been created for you.
Create a random compliment in the following format: <GREETING>,
<PETNAME> you look <DESCRIPTION> today!
<GREETING>, <PETNAME> and <DESCRIPTION> are randomly selected
from their respective arrays.
Using the string functions, replace the <GREETING>, <PETNAME> and
<DESCRIPTION> keywords in your compliment with the randomly selected
phrases from the arrays.
Display your automatically generated compliment.
The message below shows an example of a simple compliment that could
be used in your application. <GREETING> <PETNAME>, you look
<DESCRIPTION> today!
By replacing the keywords, you might end up with one of the following
compliments:
Hi Love, you look stunning today!
Hey Gorgeous, you look amazing today!
4.6.3 Open the Cryptographer_p project in the 04 – Cryptographer Folder and add
code to the OnClick event for the [Encrypt] button to do the following:
An encrypted message was created in the following manner:
a character’s logical numerical position was obtained from the character list
below:
sCharacterList := ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789.,!?:-+=”( )[ ]’;
Example: The logical numerical position of ‘A’ is 1, ‘B’ is 2 and so on.
The character’s numerical position (obtained in bullet 1) was incremented by
5.
If the radio button Caesar Cipher is selected then decrypt and display the
message.
Save and run your project.
New words
ORD() FUNCTION
The ORD function returns the ordinal value (ASCII) of a character.
Syntax: Ord(cChar)
cChar: represents a character.
Examples:
CHR() FUNCTION
The CHR function returns the corresponding character of an ASCII
code.
Syntax: Chr(iNum)
iNum: represents an ordinal number of a character.
Examples:
VAL() PROCEDURE
The VAL procedure converts a string to a numeric value.
Syntax: Val(sString, Result, iCode);
sString: represents the string that must be converted.
Result: represents the value that must be returned and can be either
an integer or real number.
iCode: Stores an integer value based on the success of the code
conversion. If the conversion is successful, iCode is 0. If the
conversion is unsuccessful, iCode stores the position where an error
first occurred in the conversion.
Examples:
Val('4450',result,iCode);
The string '4450' will be converted to 4450 and stored in result. iCode
will hold the value 0 because the conversion was successful.
Val(‘44A0’,result,icode);
STR() PROCEDURE
The STR procedure converts an integer or real number into a string,
with optional basic formatting.
iNum := 123;
rNum := 345.24;
Str(iNum, sConvert1);
ShowMessage (sConvert1);
Str(rNum, sConvert2);
ShowMessage(sConvert2);
New words
UPCASE() FUNCTION
The Upcase function converts a single letter (‘a’..’z’) character to
uppercase. If the letter is already in uppercase, it is left unchanged.
Syntax: Upcase(cLetter);
cLetter: represents a small letter in the range ‘a’ to ‘z’.
Examples:
cChar := 'z';
cLetter := Upcase('t') // cLetter will
store the letter 'T'
cCh := Upcase(cChar); // cCh will store
the letter 'Z'
cLetter2 := UpCase('S'); // cLetter2 will
store letter 'S'
UPPERCASE() FUNCTION
The UpperCase function converts lowercase characters in a string to
uppercase.
Syntax: Uppercase(sString)
sString: represents the string that must be converted to uppercase.
Example:
LOWERCASE() FUNCTION
The LowerCase function converts uppercase characters in a string to
lowercase.
Syntax: Lowercase(sString)
sString: represents the string that must be converted to lowercase.
Example:
COMPARETEXT FUNCTION
The CompareText Function compares two strings, sString1 and
sString2 for equality, ignoring case. It is not case sensitive. It returns an
integer value.
New words
Syntax: CompareText(sString1,sString2)
Note:
The function returns 0 if the strings are equal.
If sString1 is greater than sString2, the function returns an integer
greater than 0.
If sString1 is less than sString2, the function returns an integer less
than 0.
Example 1:
iNum := CompareText('Heidi','heidi')
iNum will store the value 0 because when the case is ignored, the
strings are equal.
Example 2:
sName1 := 'John';
sName2 := 'Janet';
iNum := CompareText(sName1, sName2);
iNum will store a value greater than 0 because sName1 is greater than
sName2.
Example 3:
sName1 := 'John';
sName2 := 'Janet';
iNum := CompareText(sName2, sName1);
iNum will store a value less than 0 because sName2 is less than
sName1.
Activity 4.7
4.7.1 Write Delphi statements to display the ordinal value (ASCII) of the following
characters.
a. ‘ ’
b. ‘G’
c. ‘9’
4.7.2 Read a sName string from ComboBox cmbNames and convert it to uppercase.
4.7.3 Study the code segment below and then answer the questions that follow:
IF (compareText(sString1,sString2) = 0) THEN
memDisplay.Lines.Add('Found')
ELSE
IF (compareText(sString1,sString2) > 0)
THEN
memDisplay.Lines.Add('Descending')
ELSE
memDisplay.Lines.Add(‘ascending’);
What will be the output if the following strings are read for sString1 and
sString2 respectively?
a. ‘happy’ and ‘Unhappy’
b. ‘School’ and ‘school’
c. ‘Plain’ and ‘Plane’
4.7.4 Open the project PasswordEncrypter_U in the 04 – Passwoerd Encrypter
Folder and write code for the [Encrypt] button.
• Change the letters of the alphabet from the password to the next
alphabetical letter, for example if the letter is ‘A’, the letter must become
‘B’. If the letter is ‘B’, the letter must become ‘C’, and so on. If the letter
is ‘Z’, the letter must become ‘A’.
• Display the encrypted password in the password EditBox.
• Sample output:
UNIT
4.2 Delimited strings
These characters are called delimiters since they show the start and
end (or limits) of individual pieces of data.
New words
Data is stored in the following format: ‘August#37#18’. The information in the string
is delimited by the # symbol. So ‘August#37#18’ contains three pieces of information:
month, temperature and rainfall. To split the pieces of information:
Extract the string from the EditBox edtEnter and stored in a variable called sLine.
sLine := edtEnter.text;
iPos := Pos('#',sLine);
sMonth := copy(sLine,1,iPos-1);
Delete(sLine,1,iPos);
Identify the position of the second delimiter.
iPos := Pos('#',sLine);
iTemp := StrToInt(copy(sLine,1,iPos-1));
Delete(sLine,1,iPos);
iRainfall := StrToInt(sLine);
Open the DelimiterTut_p project in the 04 – Delimiter Strings Folder and complete the
coding for the [Process] button to extract and split the string from the EditBox as
shown below.
In the GUI example above, we knew that the string had exactly two delimiters. What
happens when a string does not have a fixed number of delimiters? For example:
Different sentences have different number of words which are delimited by the
spaces.
The code to obtain each individual word in a sentence is as follows:
The program above can be adjusted to store the words of the sentence in an array
instead of displaying them. The adjusted code is:
Activity 4.8 English to Pig Latin
Pig Latin is a language game that children play in order to hide what they are saying
from people not familiar with Pig Latin. To convert a word to Pig Latin, you place the
first character of the word at the end of the word and add the letters “ay”. This means
that the word ‘Delphi’ would become ‘Elphiday’, and the phrase ‘Hello world’ would
become ‘Ellohay orldway’. For this project, you need to create a program that can
convert from English to Pig Latin, and from Pig Latin to English.
To convert text from English to Pig Latin (and back), you will need to start by
identifying all the spaces in the text.
Open the project saved in the Pig Latin_p project in the 04 – Pig Latin Folder. You
should see the following user interface.
Write code for the [English to Pig Latin] button to extract data from MemoBox
memEnglish and then convert the input text into Pig Latin. The converted text
should be displayed in the Pig Latin MemoBox memPL.
Write code for the [Pig Latin to English] button that will extract data from MemoBox
memPL and then convert the extracted text to English from Pig Latin. The converted
text should be displayed in the MemoBox memEnglish.
UNIT
4.3 Built-in Date-Time methods
DATE FUNCTION
The Date function returns the current date in the local time zone.
Because the return value is a TDateTime type, the time component is
set to zero (start of day).
Var dtToday:TDateTime;
…
dtToday := Date;
TIME FUNCTION
The Time function returns the current time in the local time zone.
Because the return value is TDateTime type, the date component is
set to 30/12/1899.
NOW FUNCTION
The Now function returns both the system date and time to a variable
of type TDateTime.
var
dtToday : TDateTime;
begin
dtToday := Now; //Gets current
system date and
//time
end;
dtToday := dtpRegistered.Date;
By Assignment:
dtToday := StrToDate('2019/06/22');
dtToday := Date;
The table below lists the most commonly used conversion functions
between the two data types.
Table 4.3: The most commonly used conversion functions
FORMATDATETIME FUNCTION
The FormatDateTime function converts data of type TDateTime into
data of type String. The returned String can be formatted to return the
Date/Time data in a user-defined format.
Example:
Var
dtToday : TDateTime;
sToday : String;
…
dtToday := Now;
sToday := FormatDateTime('dddd dd mmmm
yyyy @ hh:nn:ss', dtToday);
showMessage(sToday);
Assuming the user runs the program on 16 June 2020 at 10:16:43, the
output value will display as:
Tuesday 16 June 2020 @ 10:16:43
Notes:
The TDateTime data type is capable of storing date and time
information in a single variable.
If we don’t provide a value for the Date, the variable will revert to the
earliest system date.
If we don’t provide a value for the time, the variable will revert to
midnight.
Example 1:
Var
dtToday : TDateTime;
sToday : String;
…
dtToday := Time;
sToday := FormatDateTime('dd mmmm yyyy
hh:nn:ss',dtToday);
showMessage(sToday);
…
In this case, since the variable dtToday was assigned only to Time, the
date value reverted to the earliest system date (30 December 1899).
The default date depends on the hardware the program is running on.
Example 2:
Var
dtToday : TDateTime;
sToday : String;
…
dtToday := StrToDate('16/06/2017');
sToday := FormatDateTime('dd mmmm yyyy
hh:nn:ss',dtToday);
showMessage(sToday);
…
In this case, since the variable dtToday was assigned only to a specific
date, the time value reverted to the earliest system time which is
midnight.
OR
dtToday := Date + Time;
ISLEAPYEAR FUNCTION
The IsLeapYear function returns true if a given calendar value is a leap
year. Year can have a value 0…9999.
…
iYear := StrtoInt(InputBox('Year','Enter a
Year',''));
if isLeapYear(iYear) then
ShowMessage(IntToStr(iYear) +' is a leap
year')
else
ShowMessage(IntToStr(iYear)) +' is not a
leap year');
The timer can be switched on and off by toggling its Enabled property.
If the Timer is enabled, the code in the OnTimer event will execute
automatically at intervals determined by the Interval property. This
property is specified in milliseconds and defaults to 1000 milliseconds
or 1 execution per second.
Var
dtToday : TDateTime;
sToday : String;
…
dtToday := Now;
sToday := FormatDateTime('dddd dd mmmm yyyy
@ hh:nn:ss', dtToday);
lblOut.Caption := sToday;
…
Activity 4.9
Var
dtToday : TDateTime;
sToday : String;
arrDetails : Array[1..7] of String;
…
dtToday := Now;
sToday := FormatDateTime('dddd dd mmmm yyyy
hh:nn:ss', dtToday);
Write code to separate the delimited data in sToday and store each part in
Array arrDetails.
Activity 4.10
Declare two variables of type TDateTime: One to store the current date and the
other to store the user’s Date of Birth.
Extract date of birth from the DateTime picker.
Get the system date.
Use the extracted data to determine and display:
The user’s age
The number of days to the user’s birthday. If the user’s birthday has already
passed for the current year, then display a suitable message.
The day (example: Sunday) when the user was born.
Whether the person was born on a leap year or not.
QUESTION 1
Open the Wildlife_p project in the 04 – Wildlife Folder. The ListBox lstEnclosures
stores information about the details of each enclosure in the Wildlife Park in the
following format: <Type of animal>;<Number of animals currently in the enclosure>#
<Size of the enclosure in square metres>;<Category of animals based on size>#
Example of the data for the first five enclosures in the ListBox lstEnclosures:
• Cheetah;3#80.2;L#
• Ratel;7#50;S#
• Serval;5#80.75;M#
• Caracal;4#200;L#
• Black-footed Cat;4#30;S#
1.1 Write code for the [Process] button to do the following:
a. Read each line of text from the ListBox lstEnclosures and display the text
in the format shown in the sample run below.
b. Display the total number of animals found at the Wildlife Park.
c. Determine and display the number of animals in each category ‘L’, ‘M’
and ‘S’.
QUESTION 2
2.1 Open the project PhoneNumbers_p project in the Phone Numbers Folder.
The given program generates an array of phone numbers for you to work with.
The array called arrPhoneNos holds 20 strings. Data in the array will look like
this:
arrPhoneNos [1] := ‘086 New Hill’;
arrPhoneNos [2] := ‘086 Dial Bar’;
arrPhoneNos [3] := ‘086 Bay View’;
arrPhoneNos [4] := ‘086 Kya Sand’;
arrPhoneNos [5] := ‘086 SowetoN’;
arrPhoneNos [6] := ‘086 Casa Sol’;
arrPhoneNos [7] := ‘086 The Havn’;
arrPhoneNos [8] := ‘086 Get Food’;
arrPhoneNos [9] := ‘086 Thai Plc’;
arrPhoneNos [10] := ‘086 Cleaner’;
arrPhoneNos [11] := ‘086 Casa Rok’;
arrPhoneNos [12] := ‘086 Rix Taxi’;
arrPhoneNos [13] := ‘086 Air Time’;
arrPhoneNos [14] := ‘086 Dial Bed’;
arrPhoneNos [15] := ‘086 Dial Car’;
arrPhoneNos [16] := ‘086 Dial Hlp’;
arrPhoneNos [17] := ‘086 Kya Rosa’;
arrPhoneNos [18] := ‘086 Bay Sand’;
arrPhoneNos [19] := ‘086 Cater 4 U’;
arrPhoneNos [20] := ‘086 1to1 Air’;
a. Write code for the [Convert] button to convert all the alphanumeric
characters in the arrPhoneNos array into normal telephone numbers.
Replace the alphabetic characters (upper case and lower case) in the
telephone numbers with the corresponding numbers given below:
A, B, C 2
D, E, F 3
G, H, I 4
J, K, L 5
M, N, O 6
P, Q, R, S 7
T, U, V 8
W, X, Y, Z 9
The numeric values in the telephone numbers remain as they are.
Note: The resulting numerical phone number must be formatted as
follows: 3 digits, space, 3 digits, space, 4 digits (for example 086 345
6546)
Store the normal telephone numbers in a new array arrNewPhoneNos.
b. Write code for the [Display] button to display the original alphanumeric
number and the new numerical version.
Example of output:
c. Write code for the [Duplicate] button: Use the numerical phone numbers
to check that there are no duplicates in the array. If duplicates are found,
the program must display the duplicate numbers. If no duplicates are
found, a suitable message must be displayed. At the end of the list there
must be a summary stating how many duplicates were found (if any).
Example of the output:
QUESTION 3
3.1 The town electricity account control department requires help in calculating
arrears interest on outstanding payments. Arrears interest is calculated daily
and added to the outstanding amount owing. In terms of their policy, arrears
interest is calculated per day as follows:
Learning outcomes
INTRODUCTION
You learnt that a variable stores information temporarily in your
computer’s memory. When working with large volumes of data, it can
be time-consuming to enter the data from the keyboard each time the
program is executed. We can use information stored in text files as
input.
Text files are stored on a storage medium. Text files provide a simple,
convenient and permanent way of storing textual data and are
commonly used for importing and exporting data to and from
programs. A text file does not have any formatting or structure and
therefore you can transfer them between programs. You can store
information permanently in a text file and read and manipulate this
information using a Delphi program. By the end of this chapter, you
should be able to use the different text file functions and procedures to
open a text file, read data from a text file and write data to a text file.
UNIT
5.1 Introduction to text files
Take note
Note:
The text file must be saved in the same folder as the project file.
Activity 5.1
5.1.1 Create a text file called IndustrialRevolution.txt using NotePad. The text file
must contain the following text:
5.1.2 Create a text file called StudyTips.txt using the Delphi code editor. The text file
must contain the following text:
Examples:
Note:
If the text file is not saved in the same folder as the project file, then
you need to indicate the path for the text file.
Example:
memDisplay.Lines.LoadFromFile(‘c:\DelphiProjects\Cities.txt’);
SAVING THE CONTENTS OF A MEMOBOX OR RICHEDIT
COMPONENT AS A TEXT FILE
The contents of a MemoBox or RichEdit component can be saved as a
text file.
Examples:
Activity 5.2
Open the TextLoadSave_p project from the 05 – Text Load Save Folder and write code
to do the following:
5.2.1 [Load Text File] button: Display the contents of the text file Sports.txt using the
MemoBox component. Make the MemoBox component scrollable vertically.
5.2.2 [Create Text File] button: Save the contents of the RichEdit component to a file
Fruits.txt and display a message ‘Saved to file’.
New words
physical file – to name an external
file name found on a storage device
and contains the actual data
logical file – is a variable (in RAM)
that points to the physical file on your
storage medium
end of line <eoln> – to indicate the
end of the line when the [Enter]
button is pressed
end of file <eof> – to indicate the
end of a file when the file is saved
The file name that you will use in your Delphi program must be
declared as you would any other variable in your program:
Var
<fileVariableName>: Textfile;
The fileVariableName refers to the logical file name that you use in
your Delphi program and not the physical file name on your storage
device. The logical file name is a variable (in RAM) that points to the
physical file on your storage medium.
The <eoln> and <eof> markers refer to Boolean functions eof() and
eoln() and return a value of either true or false. Example:
Activity 5.3
Complete the following activity using pen and paper.
5.3.1 Explain what the purpose of the AssignFile procedure is.
5.3.2 Explain the difference between the Rewrite, Reset and Append procedures.
5.3.3 What type of value is returned by the Eof function?
5.3.4 Explain the purpose of the CloseFile procedure.
UNIT
5.2 Reading from a text file
Step 2: Link (or assign) a physical file to this text file variable. By
doing this, your computer knows which file on your storage medium
to access when you read or write information.
Example:
AssignFile(tLearners,'Learners.txt');
Step 3: Indicate how you would like to use the file. The three options
available are Rewrite, Reset and Append.
Examples:
Reset(tLearners);
OR Rewrite(tLearners);
OR Append(tLearners);
Step 4: Read the contents of the line at the position of the file
pointer and store the contents in the variable sLine. Once the line
has been read, the file pointer points to the next line.
Example:
Readln(tlearners,sLine);
Step 5: Close the file. Whenever you are done with your file, you
need to make sure that you close the link between the text file
variable in Delphi and the physical file, allowing other applications to
read this file.
Example:
CloseFile(tLearners);
FILEEXISTS FUNCTION
Your program can crash if you try to read from or write to a file that
does not exist. You can use the FileExists function to determine
whether a file exists or not.
New words
Note:
The FileExists function returns the value TRUE if the physical file
name FileName exists
The program searches for the file name in the current directory
Example 1:
if FileExists('Learners.txt') then
ShowMessage('File is found on
storage medium')
Else
ShowMessage('File not found on
storage medium');
Example 2:
bFileFound := FileExists('Learners.txt');
if bFileFound then
ShowMessage('File is found on
storage medium')
Else
ShowMessage('File not found on
storage medium');
EXCEPTION HANDLING
Another way to prevent a program from crashing when a file does not
exist is to use Exception Handling in Delphi.
New words
Note:
The Try command tells Delphi to try and run code where errors may
occur. If no errors occur, the code runs like it normally would. The
exception block (except) is ignored, and control is passed to the
statement following the end keyword
However, if an error occurs in the Try section, Delphi ‘catches’ the
error and the except code will take over.
The try…except statement can be used to check whether a file
exists or not:
Try
Reset(tLearners);
Except
ShowMessage('File does not exist');
Exit;
End;
Note:
To read all the text from a text file, a line at a time, you need to loop
through the text file reading a line at a time and adding the line of
text to a ListBox until the EOF marker is reached.
If you need to read a specific line of code from a text file, then you
also have to loop through the text file until the specific line is found or
until the EOF marker is reached.
Remember that a text file is sequential in nature and you have to
read data in the order in which it was written to the text file. You
cannot jump directly to the line you want to read.
RICHEDIT COMPONENT
The RichEdit component works in the same basic way as a Memo
component but offers additional formatting options. We will use the
RichEdit component to tabulate output. To do this, you will need to
change the following properties of your RichEdit component.
Example 5.1
5.4.1 The data for each client is stored on a separate line as follows in a text file
Clients.txt:
<Client No>
<Name and Surname>
<Client Type>
<Client No>
<Name and Surname>
<Client Type>
…
a. Open the Clients_p project from the 05 – Clients Folder and create an
OnClick event for the [Display Client] button to display the Client No, Full
Name of the client and the Client Type from the text file as shown.
b. Save and run the program.
5.4.2 The data for each client is stored as follows in a text file ClientsDelimited.txt in
the 05 – Clients Delimited Folder:
5.4.3 The details of users at an Internet Café is stored in a text file LoginDetails.txt in
the following format:
<name>,<age>,<email address>,<password>
Hint: You can view a list of valid emails and passwords by opening the
LoginDetails.txt file in Notepad.
Open the VerifyLogin_p project from the 05 – Verify Login Folder.
Create an OnClick event for the [Login] button to do the following:
a. Read the email address and password from the EditBoxes.
b. Compare the input email and password combination against the email
and password combinations stored in the text file called LoginDetails.txt.
c. Show a message, using an output DialogBox, indicating whether a correct
or incorrect combination of email and password was entered.
d. Save and run the project.
UNIT
5.3 Writing to a text file
Now that you know how to create a file and assign it to a text file
variable, you are ready to start adding data to it. You already know that
a text file can be created using a Text editor (Notepad or Word
processing program) or the Delphi Code Editor. We are now going to
learn how to create a text file using Delphi programming code.
You need to consider the format in which text will be written to the text
file. The format used must facilitate easy reading and interpretation at a
later stage.
CREATING AND ADDING DATA TO A NEW FILE
You need to create a file before writing information to the file and
determine the format that will be used to write information to the text
file.
5.1.1 Open the StoringLogin_p.dproj project from the 05 – Storing Login Folder.
5.1.2 The OnClick event for the [Login] button demonstrates how information is
written to the text file. The user enters an email address and password in the
EditBoxes. The email address and password will be written to the new text file
Login.txt in the following format:
<email ad-dress>,<password>
ADDING DATA TO AN EXISTING FILE
Guided activity 5.2
Open the TeamTracker_p project from the 05 – Team Tracker Folder. The following
interface will display when the program is run.
The aim of this application is to track the goals scored during a match between two
teams.
The user starts using the application by clicking the [Load Teams] button. This
loads a list of participating teams into the ListBoxes lstHome and lstAway from a
text file.
The two teams currently playing are selected from the ListBoxes lstHome and
lstAway.
Every time a team scores a goal, a [Goal!] button for the away or home team is
clicked depending on who schored the goal. If the Home team scores a goal,
btnHome button is clicked and their score is increased by 1. If the Away team
scores a goal, btnAway button is clicked and their score is increased by 1.
The scores are actively updated in the lblScore label.
After the match is complete, the [Save and Reset] button is clicked which adds the
results of the match to a text file named results.txt and then resets the application
by deselecting the teams in the two ListBoxes and setting both teams’ scores back
to 0.
The [Add Teams] button allows the user to add a new team to the roster of
participating teams. The team is added to both ListBoxes as well as to the text file
containing the list of teams.
Write code to do the following:
Declare three global variables as shown below:
APPENDING DATA
You can add data to an existing file. Data is normally added to the end
of the file. You need to position the file pointer to the end of the text file
before writing to the file. The file pointer can be moved in one of two
ways:
New words
Looping through the contents of the file until the EOF marker is
reached
Using the append procedure. The append procedure opens an
existing file for writing, sets the file pointer to the end of the file and
allows you to add data to the file.
The application will now enable users to add their own team names to the existing
‘teams.txt’ file. Open your TeamTracker_p project in the 05 – Team Tracker Folder
and do the following:
In the OnClick event of the [Add Teams] button write code to do the following:
Create a local variable called sTeamName.
Use an input box to ask the user to enter a team name and store the value in
the sTeamName variable.
Add the value of sTeamName to both the ListBoxes.
Open the tTeams file using the append procedure.
Write the value of sTeamName to the tTeams file using the WriteLn procedure.
Close the tTeam file.
The code for saving to an existing file should now look as follows:
This code will add every team name entered by the user to both the ListBoxes as
well as to the teams.txt file.
Save and test your application. Once you have added a few teams, open the text
file on your storage medium to verify that the teams have been added to the file.
Example 5.3 Team tracker appending results
To see how you can save the data from your Team Tracker application to file, work
through the following example
Open the existing TeamTracker_p project.
Declare the following global variables:
In the OnClick event of the [Save and Reset] button write code to do the
following:
Assign the tTeamTracker variable to a file called results.txt using the
AssignFile method.
Test if the file results results.txt exists. If the file does not exist, a new file
should be created.
If FileExists condition
If not FileExists(‘results.txt’) then
begin
Rewrite(tTeamTracker);
WriteLn(tTeamTracker, 'home team,away
team,home score,away score');
end
Writing to file
else
begin
sHomeName :=
lstHome.Items[lstHome.ItemIndex];
sAwayName :=
lstAway.Items[lstAway.ItemIndex];
Append(tTeamTracker);
WriteLn(tTeamTracker, sHomeName + ',' +
sAwayName + ',' + IntToStr(iHomeScore)
+ ',' +
IntToStr(iAwayScore));
CloseFile(tTeamTracker);
end;
The next step is to reset your application back to the starting point, so that a new
score can be added to the text file. To do this:
Set the values of the iHomeScore and iAwayScore variables to 0 and clear the
lblScore label’s caption.
Add the following two lines of code to btnSaveAndReset button’s event.
Deselect ListBoxes
lstHome.ItemIndex := -1;
lstAway.ItemIndex := -1;
By changing the index of the selected item to -1, you are telling the ListBox to
deselect all items. As a result, each time you press the [Save and reset] button, you
will save the data to your Text File before resetting the application to its starting
position.
Save and test your application. Using the application, add scores for a few
matches to your Text file.
The Text file will be saved in the same folder as the executable file for your
application.
Activity 5.5
5.5.1 Open the FavouriteSong_p project from the 05 – Favourite Song Folder.
Create an OnClick event for the [Select Song] button to write code to do the
following:
a. Select your favourite song name from the Radio Group and add the name
of the song to the end of text file FavouriteSong.txt.
b. Your application should ensure that:
i. The user has made a selection from the Radio Group.
ii. The text file exists before attempting to write to it.
c. Save and run your program.
5.5.2 One of the best ways for people to lose weight is to count the calories they
eat. If they eat fewer calories than they burn in a day, they should lose weight.
You have decided to help people lose weight by creating a calorie counting
application. The calorie counter will consist of four sections:
A section to allow users to add the names of foods, as well as the calories
they contain, to an existing text file.
A section that reads the text file and displays the meal options to the user.
The user can then select a meal and inform the program that they ate the
meal.
A section that displays all the meals eaten in a day, as well as the calories
consumed per meal.
A graph that shows how the food eaten per day compares to the daily limit
of 2000 calories.
Open the project CalorieCounter_p from the 05 – Calorie Counter Folder. The
following interface will display when the program is run.
a. A list of available foods and their calories are stored in a text file Food.txt
in the project folder.
b. The text file contains delimited data in the following format:
<Food Name>,<Calories>
The comma (,) acts as a delimiter, separating the food name from the calories.
The first three lines from the text file:
BigMac Burger,600
Medium Pizza,1800
Green Salad,50
d. In addition, some data structures have been declared for you. These data
structures and their purposes are listed below:
e. Write code to add the functionality described for each of the events listed
below.
Form Show
• Connect to the text file Food.txt, opening the text file for reading.
• Loop through the file, reading each line and processing it, extracting
the food item’s name and its calorie value.
• Add the food item name to the lstOptions ListBox.
• Increment the iMax variable and use it to add the food item name to
the arrFood array and its corresponding calorie value to the
arrCalories array.
• Load image file 0.jpg into the imgGraph image component.
To load an image into an Image component, we use the following
code:
imgGraph.Picture.LoadFromFile(‘0.jp
g’);
• Save and test your application.
• Based on the range of the percentage (%), load the relevant graph
image. Refer to the graph image filenames and ranges in the table,
in the introduction to this activity.
• Update the Calorie Counter in the lblCalories label and the
Percentage Counter in the lblPercentage label.
• Save and test your application.
[Reset] button
• Clear all items in the lstFoodNames and lstCalories ListBoxes.
• Assign iTotalCalories to 0.
• Load image file ‘0.jpg’ into the imgGraph image component.
• Display ‘0 / 2000’ in the lblCalories label and ‘0%’ in the
lblPercentage label.
• Save and test your application.
[Add] button
• Extract data from the edtFoodName and edtCalories EditBoxes.
• Add the extracted data to the text file Food.txt using the Food Name
and the Calories with the comma separating delimiter.
<Food Name>,<Calories>
UNIT
5.4 Creating reports
You can use the data stored in text files to produce meaningful reports.
Example: Users vote for their favourite song which is then stored in a
text file. From the data in the text file, you can determine the song of
the year or the top three songs, how many people voted for each song
and so on.
For this project, you will read the data you created in your Team Tracker project. To
do this, open the TeamScores_p project from the 05 – Team Scores Folder.
The folder contains a text file results.txt with delimited data formatted as follows:
For example:
Manchester United,Chelsea,6,1
Manchester United is the home team
Chelsea is the away team
6 was the home team’s score
1 was the away team’s score
Create an OnClick event for the [Generate Report] button and write code to do
the following:
Assign a Text File variable tScores to the physical file ‘results.txt’.
Create a conditional statement that checks if ‘results.txt’ does not exist.
If the file does not exist, display an error message and close the application.
If the file exists: Open the tScores file for reading, by using the Reset
procedure
Use a while-loop to read each line from the text file and split the line to display
the home team’s name, the scores, and the away team’s name, separated by
tab spaces in the RichEdit Box redOut. You will have to set Paragraph tab
spaces accordingly.
Save and run your application. You should now be able to read the results from
your results.txt file and display them in your application.
Congratulations, you have just used all the techniques you learned in Grade 11 to
create this report.
While the application may not look like much at this time, the techniques used to
read the data and create this application form the basis of most applications
working with data, from data analysis tools to music players and games.
Activity 5.6
5.6.1 Open the ShopSales_p project from the 05 – Report Shop Sales Folder.
The data files provided in a text file named Sales.txt which contains delimited
text in the following format:
<PRODUCT>#<SALES>
The # symbol acts a delimiter, separating the product name from its sales.
For example:
Bottled Water#32
QUESTION 1
Open the project GamingWebsite_p from the 05 – Gaming Websites Folder.
An advertising agency is tracking the popularity of various gaming websites.
Data on the websites has been captured in a text file named sites.txt with delimited
text formatted as follows:
<SiteName>#<AverageRating>#<TotalRating>#
<NumberOfRatings>
Constructoid#3#80#27
1.1 In the form’s OnShow event write code to:
• Test if the file sites.txt exists. If it exists, connect to, and open the file for
reading.
• Loop through the text file, reading each line and adding it to the lstSites
ListBox.
• In the OnClick event of the [Display] Button write code to:
• Extract the selected item from the lstSites ListBox.
• Process the extracted data, separating the delimited data.
• Display the Site Name, Average, Total and Number of Ratings in separate
lines in the redOut RichEdit component.
Six image files are provided in the project folder holding images representing ratings
ranging from 0 stars to 5 stars. For example, the file name for the image with 5 stars
is 5.jpg.
Use the Average Rating to generate a file name by combining the rating with ‘.jpg’.
Use this filename to load the appropriate image to the imgRating Image Box.
QUESTION 2
Open project WebsiteUsers_p from the 05 – Website Users Folder.
Details on registered users for a popular website are stored in a text file Users.txt.
Storing data into this text file without any security would put the system at risk. As a
result, a user’s name is obfuscated (hidden) by inserting dummy data between the
actual data.
New words
The actual data is found at the even positions of the provided text. For example:
FTBaYlHoKnU represents the name Talon
rMMhUlOeCnDgKiB
SAWsIaNnCdHaI
VABnOdKiFlVeK
In the OnClick event of the [Load Data] button write code to:
• Check if the Users.txt text file exists. If the file does not exist, display an error
message and terminate the program.
• Connect to the file and open it for reading.
• Loop through the text file, extracting a single line from the file each time the loop
runs.
• Process the extracted line, copying only the characters at even positions in the
extracted line.
• Display the processed line (decrypted) in the redOut RichEdit Box.
QUESTION 3
Open project StaffLogin_p from the 05 – Staff Login Folder.
A business requires a login system for employees when they interact with a work
computer. Details on users have been captured in a text file named staff.txt. The text
file contains delimited data formatted as follows:
<NAME>#<ID NUMBER>#<PASSWORD>
For example:
Mike#9908045421087#ke
<NAME>#<ID NUMBER>#<PASSWORD>
Note: Due to the design of the program, you’ll have to terminate the application and
run it again for the new name to appear in the ComboBox.
3.4 In the OnClick event of the [Report on Users] button write code to:
• Display the contents of the arrays arrNames, arrGender and arrAge in neat
columns, with suitable headings.
• Calculate and display:
The average age of all staff members.
The number of male staff members and the number of female staff
members.
3.5 In the OnClick event of the [Report on Logins] button write code to:
Open file log.txt text file for reading. Loop through the file, displaying all logins.
Count and display the total number of logins.
3.6 In the OnClick event of the [Search for User Login] button write code to:
• Prompt the user to input the name of a staff member using a DialogBox.
• Loop through the log.txt text file to count the number of times the staff
member has logged in.
• If the staff member has never logged in, display a DialogBox with the
message ‘User has not logged in’.
• If the staff member has logged in, display the number of times their name
appears in the log file using a DialogBox.
Sample Data 1
Sample Data 2
CHAPTER UNITS
Learning outcomes
INTRODUCTION
You learned that a method is a subprogram (small piece of code)
written to perform a specific task. The string and mathematical
methods that you learned about in previous chapters are built-in (or
pre-defined) methods found in Delphi.
In this chapter, you are going to focus on user-defined methods. User-
defined methods are written by the user to perform a specific task.
Just like built-in methods, user-defined methods can be defined and
used anywhere in a program.
UNIT
6.1 Introduction to user-defined methods
Activity 6.1
New words
private
procedure NameOfProcedure;
procedure <className>.<NameOProcedure>;
var …. //variables with local scope
begin
// body of the procedure
end;
Example 6.2
Below is code for the ThreeNumbers_p project that contains the following:
A procedure called SumOfNumbers that determines and displays the sum of
three numbers
A procedure called Highest that determines and display the highest of three
numbers
A procedure called Line that displays a line made up of the ‘=‘ symbol
[Determine] button: that reads three numbers and calls procedures
SumOfNumbers, Line and Highest
When the program is executed, it will display the following:
Notes:
In the example, because iNum1, iNum2 and iNum3 are declared non-locally
(globally), their values can be changed from any procedure in the program.
The procedure Line is called twice in the procedure Determine.
You can type the procedure or alternatively let Delphi quickly create a procedure
framework for you.
Once you declare a procedure, you can easily create a framework for the
procedure in the following manner:
Place your cursor anywhere in the name of the procedure in the procedure
declaration statement.
For example:
Press <Shift> + <Crtl> + <c> simultaneously. The following framework will
appear:
procedure TfrmThreeNumbers.Smallest;
begin
end;
If you don’t use the class name before the procedure name, you cannot access
the components of the class as you would normally do.
Activity 6.2
c. Write code for the OnClick event for the [Create] button to display a
square, triangle and a square as shown below:
6.2.5 Open the UniqueNumbers_p project in the 06 – Unique Numbers Folder and
do the following:
a. Write a procedure Generate to randomly generate 10 unique values in the
range 10 to 99 and store the values in arrNumbers.
b. Write a procedure Display to display the elements of arrNumbers
horizontally.
c. Write a procedure Sort to sort the elements of arrNumbers in descending
order.
d. Write code for the OnClick event for the [Determine] button to:
generate the unique numbers
display the original array with an appropriate message
sort the elements in the array
display the sorted array with an appropriate message.
ShowMessage syntax
ShowMessage(sOutput);
private
procedure NameOfProcedure(List of formal
parameters);
Example:
Private
Procedure
ThreeNumbers(iNo1,iNo2,iNo3:integer);
New words
formal parameter to declare
variable(s) next to the procedure
name
New words
METHOD SIGNATURE
Each method (procedure or function) has a method signature. The
name of the method and its formal parameter list is referred to as the
method signature of a method. You can get more than one method
with the same name. This is called method overloading. In method
overloading a procedure is differentiated from another procedure by its
method signature.
Example of a procedure with a parameter
procedure TFrmGreetings.SayHello(sWhat:string)
begin
ShowMessage('Hello ' + sWhat) ;
end;
New words
Note:
The name of the form is TfrmGreeting
The name of the procedure is SayHello
The procedure has one formal parameter sWhat of type String
The procedure displays the word ‘Hello’ followed by the string sWhat
that it received. For example, if it received ‘Tarzan’ then it would
display ‘Hello Tarzan’.
6.3.3 Study the following procedures and identify the mistakes made in each
procedure.
Procedure 1
SetFormHeight(iHeight : Integer);
begin
frmMain.Height := iHeight;
end;
Procedure 2
Procedure 3
Activity 6.4
6.4.1 Open SquareShapes_p project in the 06 – Square Shapes Folder and do the
following:
a. Write a procedure Square that will receive an integer value iSize and will
draw a square of size iSize. Example if iSize is 10, then the following
square will be drawn:
b. Create an OnClick event for the [Squares] button that will read the size of
the square from the EditBox and store the value in variable iSquareSize.
Display three squares with each square’s size one smaller than the size of
the previous square displayed. The size of the first square will be size
read from the EditBox.
UNIT
6.3 Functions
Calling a function
Since a function always returns a value, a call to a function is always
within another statement such as:
an assignment statement
a selection statement
an output statement.
Write a function CalculatePower that accepts two integer numbers iBase and
iExponent and returns the results of iBase raised to the power iExponent.
CalculatePower function
function TnameOfForm.CalculatePower(iNumber,
iExponent : Integer) : Integer;
var
i, iOutput : Integer;
begin
iOutput := 1;
for i := 1 to iExponent do
iOutput := iOutput * iNumber;
Result := iOutput
end;
Write a function CalculateFactorial that returns the factorial of a number. The number
is received as a parameter. The factorial (indicated by the ! symbol) of a number N is
determined as follows:
N! =1*2*3, …,*N
Factorial function
function TnameOfForm.CalculateFactorial(iNumber
: Integer) : Integer;
var
i, iOutput : Integer;
begin
iOutput := 1;
for i := 1 to iNumber do
iOutput := iOutput * i;
Result := iOutput;
end;
Activity 6.5
6.5.1 Open the Vowels_p project in the 06 – Vowels Folder and do the following:
a. Write a function CountVowels that receives a word and returns the
number of vowels in the word.
b. Write a function RemoveVowels that receives a word and returns the word
with the vowels removed.
c. Write code for the [Process] Button. Each element of the array arrWords
contains a word. For each element, display the word, the number of
vowels in the word and the word with the vowels removed. The display
must be in tabular form. Call function CountVowels and RemoveVowels.
Save and run your program.
6.5.2 Open the PowerFactorial_p project in the 06 – Power Factorial Folder and
write code to do the following:
a. Write a function CalculatePower that accepts two integer numbers iBase
and iExponent and returns the results of iBase raised to the power
iExponent.
b. Write a function CalculateFactorial that returns the factorial of a number:
The number is received as a parameter. The factorial (indicated by the !
symbol) of a number N is determined as follows:
N! =1*2*3, …,*N
function TfrmMake15.isUnique(arrVal:
arrGuesses): boolean;
var bFlag:Boolean;
i,j: Integer;
begin
bFlag := True;
for i := 1 to 8 do
for j := I + 1 to 9 do
if arrVal[I] = arrVal[J] then
begin
bFlag := False;
end;
result := bFlag;
end;
UNIT
6.4 Basic input validation techniques
For any data input, a validation check is used to ensure that the data
received is actually what is required by the application. Validation
checks are a safeguard against incompatible values that could cause
interruptions in the flow of the program or cause the program or
operating system to crash. Validation techniques do not determine
whether the data input is accurate. Different validation techniques are
used to validate data input.
function TValidation.isValidStringAZ(sValue:
String): boolean;
Var
bFlag: boolean;
i, iLength: Integer;
begin
if Length(sValue) <> 0 then
begin
i := 1;
bFlag := true;
while (i <= Length(sValue)) AND (bFlag =
true) do
begin
if not(upcase(sValue[i]) in [‘A’ .. ‘Z’,
‘ ‘]) then
begin
bFlag := False;
end;
inc(i);
end;
end
else
begin
bFlag := False;
end;
result := bFlag;
end;
RANGE CHECK
Range validations are used to ensure that data input matches the
expected range limitations imposed by the application. For example, in
the case of validating a cell phone number, you need to check whether
the number contains only digits and 10 characters in length.
PRESENCE CHECK
When a presence check is set up on a field then that field cannot be
left blank, some data must be entered into it. The presence check
does not check that the data is correct, only that some data is present.
For example:
function TValidation.CheckEmpty(sValue:
string): Boolean;
var
bFlag: Boolean;
begin
bFlag := true;
if (sValue = ‘‘) then
begin
bflag := false;
showmessage('Please enter a value');
end;
end;
Activity 6.6
New words
QUESTION 1
Open the LearnerYearMark_p project from the 06 – Learner Year Mark folder.
1.1 Create a function CalculateYearMark to calculate a learner’s year mark. The
function accepts the following parameters:
• Test 1
• Test 2
• Assignment
• Exam
The average of the two tests form a quarter of the learner’s year mark, the
assignment another quarter of the year mark and the exam forms half of the
learner’s year mark. The final year mark must be rounded up to the nearest
integer.
Do the following:
a. Write code for the function CalculateYearMark.
b. Create an OnClick event for the [Calculate Learner Year Mark] button to
read the marks for Test1, Test2, Assignment and Exam. Call the function
CalculateYearMark to calculate the year mark.
c. Display the year mark in the edtYearMark EditBox.
Open the ConvertMeasure_p project from the 06 – Convert Measurement folder.
1.2 Create a function Convert that receives number of bytes and the unit of
measurement (KB, MB, GB or TB) to convert the bytes to. The declaration of the
function Convert:
Function Convert(NoBytes:integer;UnitOfMeasure:String):String;
Use the table below to convert to the required unit of measurement.
The function must return a string containing the answer of the conversion and
the unit of measurement.
Example: if the function was called as follows:
sAnswer := Convert(1200,'KB');
//then the function will return 1.200 KB.
Do the following:
a. Write code for function Convert.
b. Create an OnClick event for the [Convert Measurement] button to:
i. Read the number of bytes from the EditBox edtBytes.
ii. Select the unit of measurement to convert bytes to kilobytes.
iii. Call function Convert to do the conversion and display the conversion
answer.
QUESTION 2
2.1 Replace delimiters of a string with new delimiters.
Example:
Replace the space delimiters in a string with the delimiter ‘*’.
The string:
The fat cat jumps high.
Becomes:
The*fat*cat*jumps*high.
Open the ChangeDelimiter_p project in the 06 – Change Delimiter Folders and
do the following:
a. Write a procedure ChangeDelimiters to accept a sentence, the current
delimiter of the string and the new delimiter of the sentence. Replace the
current delimiter with the new delimiter. Display the original sentence and
the new sentence one below the other.
b. Write a procedure ReadFileData to read the data stored in the text file
Sentences.txt and store the values in an array arrSentences. You may
assume that the text file may not contain more than 10 entries.
c. Create an OnClick event for the [ChangeDelimiters] button to:
i. Read the original delimiter and the new delimiter from the EditBoxes.
ii. Call procedure ReadFileData
iii. Call procedure ChangeDelimiters to change the original delimiter of the
strings stored in arrSentences with the new delimiter.
2.2 The Make 15 Puzzle is a game. In this game, you have nine boxes, arranged in
a three-by-three square. The goal of Make 15 is to enter values into these
boxes so that all the rows, columns and diagonals add up to 15. The trick is that
you are not allowed to use any number in the range 1 to 9, more than once.
Open the Make15_p project in the 06 – Make15 Folder. You should see the
following user interface for your puzzle.
Note: the EditBoxes are named as shown in the image alongside. EditBox Edt1
is therefore the EditBox in the top-left corner, while EditBox edt9 is the EditBox
in the bottom-right corner.
a. Write a function IsUnique that checks whether the 9 values entered by the
user are unique.
b. Write a function IsFifteen that accepts three integer parameters and returns
a String ‘True’ if the total of the three numbers is 15; otherwise it returns the
value ‘False’.
c. Create an OnClick event for the [Calculate] button to:
i. Store the values from entered in the EditBoxes edt1 to edt9 in an array
arrValues. The value of EditBox edt1 is stored in arrvalues[1], the value
of EditBox edt2 is stored in arrValues[2] and so on.
ii. Call the isUnique function to check whether the values entered are
unique values. If the values are not unique, display an appropriate
message. If the values are unique, then call the isFifteen function and
pass three values of the first row that is the first three elements of the
array arrValues. Assign the return value of function isFifteen to the
label next to the first row. Call the isFifteen fuction for the other rows,
columns and diagonals. Determine whether a user won or not and
display the message in the message label.
Save and test your application.
CHAPTER UNITS
Learning outcomes
INTRODUCTION
In Grade 10, you learned how to analyse user interfaces. A big part of
this exercise was recording all the screens the application uses and
understanding how to navigate between these screens.
Up to now all your applications have used a single screen. While this
has worked thus far, there are serious drawbacks to creating single-
screen applications:
It limits the number of components you can use in your program.
It limits the overall scope and size of your program.
User interfaces can quickly become confusing.
In this chapter, you will learn how to add additional screens (or forms)
to your application. This will allow you to create simpler, easier to use
user interfaces that group similar functions on the same screen. You
will also learn how to dynamically add elements to your screens. This
means that components like labels, images and textboxes can be
created using code. By the end of the chapter you should be
comfortable using both techniques, as both these techniques are
critical in creating professional applications.
UNIT
7.1 Multi-form user interfaces
New words
uses
Windows, Messages, SysUtils, Variants,
Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls,
GreenForm_U;
procedure
TfrmYellow.btnNewScreenClick(Sender:
TObject);
begin
frmGreen.Show;
frmYellow.Hide;
end;
procedure TfrmGreen.btnCloseClick(Sender:
TObject);
begin
frmGreen.Close; // OR self.close;
end;
Note:
The CLOSE method of a form closes any specified form. You can therefore close
any form that is opened. The form closes not the application.
The statement:
Application.Terminate;
Self.close;
Activity 7.1
A text file Users.txt stores the information of all users of FriendBook in the following
format:
New words
name,age,email,password
Vijay,100,[email protected],Alien
Arhaan,14,[email protected],Tookols
Rayan,29,[email protected],Secret
Rachael,45,[email protected],45#Pc
7.1.1 Open the FriendBook_p project in the 07 – FriendBook Folder and do the
following:
a. Add a new form FriendBookLogin_u to the FriendBook_p project.
b. Add components to the FriendBookLogin_u form as shown below:
a. Create an OnClick event for the [Sign Up] button to read the information
for the name, age, email, password and confirm password from the
EditBoxes. Check if the password and confirm password data match. If
the password and confirm password matches, write the name, age, email
and password to the User.txt text file in the required format. If the
password and confirm password data does not match, then display an
appropriate message.
b. Create an OnClick event for the label that contains the text ‘Click here to
return to the Login Form’ that will display the Login screen.
To do this:
1. In the Project Manager panel, right-click on the name of the project
and select Options from the drop down list.
2. The Project Options DialogBox is displayed.
3. Select the form that you want to set as the main form from the
main form drop down list.
Activity 7.2
7.2.1 Open the ChangeMainForm_p project in the 07 – Change Main Form Folder.
Change the main form to frmLogin.
7.2.2 Save and run the project.
UNIT
7.2 Dynamic instantiation of objects
Up until now you have created a user interface and then coded using
the user interface. In many situations the user interface will not always
remain the same, such as in the the case of a game. In a game the
user interface changes as the game progresses. The programmer may
create characters, obstacles and enemies. When a component or
object is created during run-time we refer to this as dynamic
instantiation of objects.
New words
VISUAL COMPONENTS
In Delphi, all components can be created using the Create method of
their class. To dynamically create a label component, we need to
declare the name of the label as a variable:
Instantiation of the label component object
The label is created by calling the Create method of the TLabel class.
lblMessage.Parent := Self; OR
lblMessage.Parent := frmMain;
lblMessage.Caption := ‘Hello, World!’;
lblMessage.Parent := Self;
lblMessage.Text := 'Hello, World!';
lblMessage.Left := 100;
lblMessage.Top := 100;
lblMessage.Width := 100;
lblMessage.Height := 20;
You can create any component in a similar manner as you did for the
label component. In order to assign values to the component
properties, you need to know the names of the most important
properties.
For this project, you will create an application that creates rainbow coloured boxes
every time you click on the [Create Box Option] button:
To do this:
1. Create a new project RainbowBoxes_p project and save it in a folder named
07 – Rainbow Boxes.
2. Create the following user interface.
3. Add the unit ExtCtrls to the USES section of your program. This will allow you
to dynamically create the TShape component.
4. Declare the following two global variables.
i : Integer = 0;
shpDynamicBox: TShape;
The integer variable I is declared and initialised at the same time. This type of
declaration can only be done with global variables. The variable I is assigned
the value 0.
i: integer = 0;
While most of this code sets static properties for the rectangle, the Left
property increases by 80 with each new box. The calculation for the Left
property ensures that each time the value of variable I increases, the next box
will be placed 80 pixels further to the right. The different boxes will be placed
next to each other rather than on top of each other.
6. Create the following CASE statement to set the colour of the box based on the
value of variable I.
Colour elements
Case i of
0 : shpDynamicBox.Brush.Color := clRed;
1 : shpDynamicBox.Brush.Color := $000080FF;
2 : shpDynamicBox.Brush.Color := clYellow;
3 : shpDynamicBox.Brush.Color := clGreen;
4 : shpDynamicBox.Brush.Color := clBlue;
5 : shpDynamicBox.Brush.Color := clPurple;
6 : shpDynamicBox.Brush.Color := clFuchsia;
end;
7. Set the Name property of the box equal to the text shpBox followed by the
value of variable I. This name could be used to change a box’s properties at a
later time.
Example:
INTERACTIVE COMPONENTS
Creating an interactive component with an event (such as an OnClick,
OnChange or OnTimer event), can be done in seven steps:
Step 1: Declare the component variable.
Step 2: Create the component and assign it to the variable.
Step 3: Set the component properties.
Step 4: Declare the name of a custom procedure in the Public
section of your form.
Step 5: Add the (Sender: TObject) parameter to the procedure’s
name.
Step 6: Create the custom procedure for your event in the code.
Step 7: Assign the name of the procedure to the appropriate event
property.
In the next four steps you will create a button interactive component
with an OnClick event:
Step 4: Declare the name of the custom procedure that you want to
link your button or timer to in the Public section.
7.3.1 Create an OnClick event for the [Create a Button] button to do the following:
a. Each time the [Create a Button] button is clicked, it creates a new button
and displays a message as shown below:
b. Save and run the project.
CHAPTER UNITS
Learning outcomes
INTRODUCTION
Databases play a critical role in permanently storing data in
applications. Whether it is a music library in a media player, the
graphics and dialogue for a game, or a user’s settings in an
application, databases provide a structured, logical method to store
data. In this chapter, you will learn how databases can be used in
Delphi applications. The information stored in the database will be
accessed and manipulated via programming code. The focus will be
on connecting to the database, obtaining the data and using the data
in your application.
UNIT
8.1 Creating a database
10. Click on the Home tab in the ribbon. Click on View and choose Design View.
Note:
• When generating Autonumbers, the computer always remembers the last
Autonumber generated and adds 1 to it. For instance, if there are 15
records in a table and you delete the 15th record, when you add a new
record, the Autonumber generated will be 16.
To do this:
1. Type the field name Surname as your first field.
2. Select the Short Text option as the data type.
3. In the Field Properties options, set a Field Size for Surname. It defaults to 255,
but since surnames would not take up that many characters, it is in good
design principles to set a smaller size. In the example below the size is set to
40.
4. Add a second field of type Short Text called FirstNames. Set the field size, as
necessary.
5. Add the remaining fields for tblFriends, choosing the appropriate data types
and setting the Field Sizes, if necessary.
6. When all the fields have been added, Save changes to the database.
Adding Records to the table
1. Click on Home, View, DataSheet View. This will take you to DataSheet View.
2. In Datasheet View, enter the details for at least five friends:
Activity 8.1
Create Microsoft Access databases and add at least five records to the tables in the
database.
Appropriate field names and data types should be used.
8.1.1 A database called ContactsDB which stores information about your friends in
tblInfo. Fields to store the following data should be created:
a. Name
b. Surname
c. Age
d. Phone number
e. E-mail address
f. Last date spoken
8.1.2 A database called ShopsDB which stores information about a variety of
different online or physical shops that you use in tblShops. Fields to store the
following data should be created:
a. Name
b. Physical address
c. Web address
d. Type (e.g. electronics, clothes, fast food, groceries)
e. Number of times you have used them
f. Last time you used them
UNIT
8.2 Connecting to a database
The first step to using a database in your application is to create a
connection between your application and the database. To do this, you
will use the following invisible components:
TADOConnection: As the name suggests, the TADOConnection
component is used to create a connection to an external database.
TADOTable: The TADOTable component uses the database
connection to connect to a specific table inside your database.
TDataSource: The TDataSource component creates a connection
between your database table(s) and the Delphi components. A
DataSource can contain data from an entire table, a part of a table or
data from several tables combined.
Figure 8.1: The connection between your application and the database
The first two components can be found from the dbGo list in RAD
Studio’s Tool Palette, while the TDataSource component can be found
in the Data Access list of the Tool Palette.
Figure 8.2: The dbGo list from the Tool Palette
New words
While these components can be added directly to your form, this links
them to a specific form, making it harder to use the database in a
multi-form application. Use of multiple forms is necessary for your PAT,
so it is better to put our database connection components into a data
module that we can share across forms. The database connection
components can be added to a new type of unit called a data
module. The example below shows how a data module can be
created and used in a project.
3. Inside the New Items window, select the Data Module option and click OK. This
will add a new data module to your project.
4. Save the data module in your project folder with the name conFriendBook.
5. Rename the data module form to dbmFB.
6. Select your main form and open the Code screen.
7. Add conFriendBook to the Uses section of your main form’s code. Save and
close your project.
unit FriendBook_u
interface
uses
Windows, Messages, SysUtils, Variants,
Classes, Graphics, Controls,
Forms, Dialogs, ComCtrls, StdCtrls,
Keyboard, ExtCtrls, Grids,
DBGrids, conFriendBook;
By adding the conFriendBook data module to a form, you gain access to any
database connections created inside the data module. By separating the database
connections from any form, you can import the database into each form through
the Uses section.
Open your FriendBook_p project from the 08 – FriendBook_1 Folder and open the
conFriendBook data module.
1. In the Tools Palette, open the dbGo list and drag a TADOConnection to the data
module.
2. Rename the component to conFriendBookDB.
3. Change the connection’s LoginPrompt property to False.
4. Double click on the conFriendBookDB component in your data module. This
will open the Connection String window.
4. Change the value of the TableName property to the name of the table you are
connecting to (tblFriends). If your connection was made correctly, you will be
able to select the table from a dropdown list in the Object Inspector.
5. Change the table’s Active property to True.
6. From the Data Access list in the Tool Palette, drag a TDataSource component
to your data module.
7. Rename the Data Source to dscFriends. You should now have the following
three components on your data module:
8. Select your dscFriends component and set the value of its DataSet property to
tblFriends.
CONNECTING TO AN ACCESS
DATABASE
https://www.youtube.com/watch?
v=k8pGVnNHflE
Example 8.4 Connecting an Access database and your Delphi application using
code construct
This method establishes a connection between the Access database and your
Delphi application using code construct. Since we are writing code to point the
ADOConnection to the external database, we must first ensure that our database
resides in the same folder as our project.
Move your Access Database FriendBookDB.mdb to the 08 – FriendBook_2 Folder.
1. Open the FriendBook_p project from the 08 – FriendBook_2 Folder. This
project has an empty DataModule already created and saved.
2. Double click on conFriendBook.pas in the Project Manager to open the
DataModule.
3. Since we are connecting the database using code, we do not need to add any
components to the DataModule from the Palette.
4. Switch to Code view.
5. Under USES, add: ‘ADODB’ and ‘DB’.
uses
SysUtils, Classes, ADODB, DB;
type
TconFriendBookDB = class (TDataModule)
private
{ Private declarations }
public
{ Public declarations }
conFriendBookDB: TADOTable;
dscFriends: TDataSource;
end;
7. Switch to Design view and create an OnCreate event for the DataModule.
UNIT
8.3 Reading data from a database
Once a database connection has been made, you can start using and
displaying the data in your application.
Open the FriendBook_p project in the 08 – FriendBook_3 Folder. The basic user-
interface has already been built. It is, however, missing an important component
which you will have to add. To do this, the following basic user interface has been
provided:
1. In the Tool Palette, find the Data Controls list and drag a TDBGrid to your form.
2. Change the name property to dbgFriends and resize it as shown in the image
below.
3. To display the data from your database, you need to connect dbgFriends to
your datasource. To do this:
a. In the Design screen, create an OnShow event for the form.
b. In the OnShow event, write the following line to connect the DBGrid to
DataSource in the DataModule.
dbgFriends.DataSource := dbmFB.dscFriends;
4. Save and test your application. You should now be able to see the records
from your database on the FriendBook form.
The only problem remaining with the user interface of the FriendBook form is
that a few of the columns are too wide. To solve this problem:
5. Navigate to the OnShow event for the form.
6. Inside the OnShow event, add the following lines of code.
Column width
dbgFriends.Columns[0].Width := 30;
dbgFriends.Columns[1].Width := 80;
dbgFriends.Columns[2].Width := 120;
Activity 8.2
Both questions in this activity are based on the SoftDrink Application. This main form
contains a DBGrid named dbgSoftDrink. An OnShow event is already created, but no
code has been written for it. A DataModule named conSoftDrink has been created and
saved to the project folder. The DataModule’s object name is dbmSoftDrink. An
OnCreate event is created for the data module.
The folder also contains a database named SoftDrinkDB.mdb that contains a single
table named tblSoftDrink that has been populated with several records.
8.1.1 Open project SoftDrinkApp_p from the 08 – SoftDrink_1 Folder.
Open the DataModule conSoftDrink. Your aim is to create a connection
between SoftDrinkDB.mdb (The Access database) and the Delphi project using
the Connection Wizard (method 1).
a. Add the following components, renaming them as shown in the table:
public
conSoftDrinkDB : TADOConnection;
tblSoftDrink : TADOTable;
dscSoftDrink : TDataSource;
UNIT
8.4 Writing data to a database
In this unit, you will learn about two different ways to write data to a
database.
Once this new row has been created (using either append or insert),
you can then set the values in this row, much like how you would
change the values of a variable. For example, to set the values of the
Surname and FirstNames fields in your tblFriends table, you can use
the following syntax.
Looking at the syntax, after the append method, you use the table
name followed by the name of the field (as a string in square brackets).
You then use the assignment statement (:=) to set the value of the field.
Once you have added values for all the fields, you use the post
command to permanently save the values to the database table.
In order to maintain Data Integrity, we normally validate input data before writing it
to the database. This code does not include validation; however, it is important to
note that professional applications protect data integrity by using validation
techniques.
THE WITH KEYWORD
Since our data components reside within the DataModule (dbmFB), we
have to reference it whenever we interact with our database table. In
larger applications, referencing the DataModule repetitively can
become cumbersome.
Example 8.7 Display the user’s Surname, First Names and Class using
DialogBoxes
showMessage(dbmFB.tblFriends['Surname']);
showMessage(dbmFB.tblFriends['FirstNames']);
showMessage(dbmFB.tblFriends['Class']);
WITH dbmFB DO
Begin
showMessage(tblFriends['Surname']);
showMessage(tblFriends['FirstNames']);
showMessage(tblFriends['Class']);
End;
Using the WITH command is not compulsory but can make larger
blocks of code more readable. Whether you use it or not depends on
your programming style.
8.1.4 When the user clicks on a profile in the DBGrid, the application will transfer
the selected user’s details to the individual components below.
Editing an existing record
Now that we have the data available in standard input components such as EditBoxes,
we can read changes the user may effect into these components and then update the
captured data.
8.1.5 Create an OnClick event for the button [Update Profile].
8.1.6 First we must set our ADOTable into Edit mode.
dbmFB.tblFriends.Edit;
8.1.7 Next, we transfer data from our Input components into the table.
8.1.8 Finally, we write the changes to the database.
dbmFB.tblFriends.Post;
showMessage('Profile updated');
4. Now, whenever the user clicks on a record in the DBGrid, the ProfileViews
value will increment automatically.
The table below shows the table methods that allow you to step
through your database.
For this project, you will use the functions listed above to perform calculations and
apply filters to a database. To do this:
1. Open the project DamsApp_p in the 08 – DamsApplication Folder. You should
see the following user interface.
In this application, the data module and all the database connections have
already been made. Your only task will be to create the OnClick events for the
different buttons and write code to make each button function.
The database DamsDB contains the following fields and relationship:
Take note of the primary keys and foreign key as these fields are necessary
when accessing data across tables.
2. Create OnClick events for the [First], [Previous], [Next] and [Last] buttons.
Navigating to the first record in the tblDams
In the OnClick event for btnFirst, add the following line of code:
dbmDamsDB.tblDams.First;
dbmDamsDB.tblDams.Prior;
dbmDamsDB.tblDams.Next;
Navigating to the last record in the tblDams
In the OnClick event for btnLast, add the following line of code:
dbmDamsDB.tblDams.Last;
3. Save and test your application. The [First], [Previous], [Next] and [Last] buttons
should now function, allowing you to navigate through tblDams.
rSum := 0;
8.2.3 Our next step is to move the iterator (pointer) to the first record in the table.
This is necessary because (by user action or processing), the iterator could be
at any point in the table. We need to make sure that processing will start at
the first record.
dbmDamsDB.tblDams.First;
8.2.4 Next, we need to use a WHILE-Do-loop to iterate through every record. This is
necessary as we have to process every record, extracting its capacity value
and adding it to rSum.
To add each dam’s capacity value to rSum, we include the following line inside the
WHILE-Do-loop:
8.2.5 Next, within the WHILE-Do-loop, we instruct the iterator to move to the next
record in order to continue the process of calculating the total capacity.
dbmDamsDB.tblDams.Next;
8.2.6 After the WHILE-Do-loop terminates, we will now have the total capacity
stored in rSum. We can now use this total to calculate the Average.
8.2.8 Save and run your application. Clicking the [Average Capacity] button should
now calculate and display the average capacity of all dams.
8.3.1 The field Capacity indicates the maximum amount of water that a dam can
store.
8.3.2 The field DamLevel indicates the current amount of water in the dam.
8.3.3 To express how full the dam is as a percentage, we can use the following
formula:
var
sName : String;
rLevel, rCapacity, rPerc : Real;
3. Next, write the code below, which will extract, process and output the necessary
data.
4. Save and run your application. Clicking on a Dam in tblDams dbGrid and then
clicking the [Calculate % Full] button should now calculate and display the
percentage level of the selected dam.
Guided activity 8.4 Display all Dams completed after the year 2000
(Project DamsApp_p)
The field YearCompleted indicates the year when each dam’s construction was
concluded.
We will now loop through tblDams and test each dam’s YearCompleted value based
on our criteria. If the value meets our criteria, we will display the dam’s name.
8.4.1 Create an OnClick event for the [List of Dams post 2000] button.
8.4.2 The code and explanations are provided below:
8.4.3 Save and run your application. Clicking on the [List of Dams post 2000] button
should now display a list of dam names for dams completed after the year
2000.
SEARCHING FOR RECORDS BASED ON USER INPUT
Searching based on user input uses an algorithm very similar to the
one used in the previous Guided activity. The only difference is instead
of using a constant condition, the condition will compare the field being
tested against the user’s input.
Guided activity 8.5 Search for a Dam Name specified by the user
(Project DamsApp_p)
8.5.1 Create an OnClick event for the [Search by Dam Name] button.
8.5.2 Our aim is to prompt the user to input the name of a Dam. We then loop
through tblDams and identify all dams that match the input name. The dam’s
name, level and capacity will be displayed if it is found. If no results are found,
an appropriate message is displayed instead.
The code and explanations are provided below:
8.5.3 Save and run your application. Clicking on the [Search by Dam Name] button
should now prompt the user to input the name of a dam. The application
should then locate and display the target dam’s details or display the ‘Dam
not found’ DialogBox if the target was not located.
IDENTIFY FIELDS WITH NULL VALUES
When processing values from a database table, it is sometimes
necessary to identify fields which contain a null (empty) value. Note
that null should not be confused with 0 or an empty string (''). If a
numeric field is assigned to 0 or a String field is assigned to an empty
string, both are considered to hold values. Having a null value means
that the field is empty and has not been initialised. Fields with null
values can cause run-time errors when looping through a table or
cause logical errors when processing calculations such as averages.
New words
null – to represent an empty value
8.6.1 Create an OnClick event for the [List with Null Height] button.
Our aim to display the dam names for all dams which have a null value for the
HeightOfWall field.
The code and explanations are provided below:
8.6.2 Save and run your application. Clicking on the [List with Null Height] button
should now loop through tblDams and identify the dams with null
HeightOfWall values and display the corresponding dam names into the
Output Area.
COUNTING FIELDS THAT MATCH SPECIFIC CRITERIA
Statistical calculations often require us to count the number of records
which meet certain criteria. The process is very similar to the methods
we’ve already explored.
In this activity, the user will input a letter of the alphabet. We will then loop through
the tblDams table and count the number of dams that have a name beginning with
that letter.
8.7.1 Create an OnClick event for the [Count names by Letter] button.
The code and explanations are provided below:
8.7.2 Save and run your application. Clicking on the [Count names by Letter] button
should now prompt the user to input a letter of the alphabet and then loop
through tblDams. It will then identify dam names beginning with provided
letter and increase the counter every time a dam is identified. Output will be
displayed in the Rich Edit Box.
READING DATA ACROSS RELATED TABLES
Most professional databases have multiple tables and it is often
necessary to read and manipulate data across the tables. In Grade 11,
we will be learning the basics of reading data across multiple tables. In
Grade 12, this concept will be expanded upon, including the use of
SQL statements to manipulate datasets.
Take note
When the user clicks on a Town in the dbGrid linked to tblTowns, we will identify the
DamID (Foreign Key) connected to the town. We will then loop through tblDams and
search for the DamID (Primary Key) in tblDams. Once we find it, we will display the
Dam Name and its associated River from tblDams.
8.8.1 Create a OnCellClick event for dbGrid dbgTowns.
8.8.2 Our first step will be to extract the DamID from tblTowns. This will enable us to
identify the foreign key we will be searching for.
sDamID := dbmDamsDB.tblTowns['DamID'];
8.8.3 Our next step is to point the other table to the first record, so that we can loop
through it and search for the foreign key (sDamID).
dbmDamsDB.tblDams.First;
8.8.4 We can now loop through tblDams, searching for the DamID extracted from
tblTowns.
8.8.5 Inside the WHILE-Do-loop, we compare each Primary Key (DamID ) in tblDams
with the extracted Foreign Key from tblTowns (sDamID). When we identify a
match, we have found the corresponding record in tblDams. We can then
output the Dam Name and River Name (or any other fields, if necessary).
8.8.6 Finally, within the WHILE-Do-loop, we move the iterator to the next record:
dbmDamsDB.tblDams.Next;
Notes:
A flag can be used to terminate the loop once a match is found. This will improve
the efficiency of the solution.
If referential integrity is enabled in the database relationship, there is no need to
cater for a ‘match not found’ message as the foreign key is guaranteed to exist in
the other table.
8.8.7 Save and test the application. By clicking on a town in the dbGrid linked to
tblTowns, the corresponding dam data should be displayed in the RichEditBox.
QUESTION 2
Open the project ShopApp_p in the 08 – ShopApp Folder.
The following user interface is provided.
The application is already connected to the Access database ShopDB, which uses has
the following tables and relationship:
The DataModule provided is named dbmShopDB and contains two ADOTable
components named tblProducts and tblSuppliers.
Write code for each event (2.1 to 2.11) to perform the tasks described below:
2.1 [2.1 Specials] Display a list of product names which are on special.
Products are on special when the OnSpecial field is set to TRUE.
The product names (Descrip) should be displayed to the Output Area.
2.2 [2.2 Count Specials] Count and display the number of products that are on
special.
2.3 [2.3 Average Stock] Calculate and display the average stock available for all
products.
2.4 [2.4 Total Product Value] Determine and display the Total Product Value (in
Rand) for the selected product. The total product value is calculated by
multiplying a product’s Supplier Price (SuppPrice) by the number in stock
(Stock).
2.5 [2.5 Decrease Stock] When products are sold, their stock needs to be
decreased accordingly.
Write code to decrease the stock value of the selected product by 1.
Display a confirmation message.
2.6 [2.6 Add Supplier] Write code to add a new Supplier to the Supplier table
tblSuppliers.
a. Generate a SuppID by combining the letter ‘S’ with the next available
number in the table. (Hint: Use the RecordCount function + 1)
b. For the fields, SuppName and CellNo, use the InputBox function to get
values from the user.
c. Assign the AccBal (Account Balance) field to 0.
d. Write the record to the database and display a confirmation message.
2.7 [2.7 Delete Product] Write code to Delete the selected product record after
displaying a Confirmation Message.
2.8 [2.8 Search for Product] Write code to prompt the user to input a Product
Name. Loop through tblProducts and if the product is found, display the
product’s stock. If the product is not found, display an appropriate message.
2.9 [2.9 Calculate Selling Price] The selling price for all products has been initialised
to 0. The actual selling price is calculated using the following formula:
Write code to loop through tblProducts and calculate and permanently store the
Selling Price (SellPrice) for all products.
2.10 Write code to display the Supplier’s Details of a particular product. When the
user clicks on a Product in dbgProducts, extract the SuppID (foreign key)
associated with that product. Loop through tblSuppliers and find the
corresponding Supplier ID and display the Supplier’s name and mobile number.
Note: each product has only 1 supplier.
2.11 Write code to display all products supplied by a particular supplier. When the
user clicks on a Supplier in dbgSuppliers, extract the SuppID (Primary Key)
associated with the supplier. Loop through tblProducts and identify all products
that are associated with that supplier. Display a list of the products names.
Note: a supplier may supply more than one item.
ANNEXURE Problem solving
A.1
ALGORITHMS
In Grade 10 you learned that an algorithm is a plan drawn up to solve a
particular problem in a finite number of steps. An algorithm can be
represented using:
a flowchart: A flowchart is a tool that can be used to visually show
how an algorithm works.
pseudocode: Is written using the same logic and structures as a
programming language, but it does not have to follow any
programming language’s syntax or rules.
a programming language: An algorithm is translated into
programming code for execution.
Remember that you must follow the problem solving steps to create
high quality algorithms. These are shown in the Figure A.1 below.
WHAT’S AN ALGORITHM?
https://www.youtube.com/watch?
v=6hfOvs8pY1k
New words
FLOWCHART
In Grade 10 you also learned that a flowchart is a tool that is used to
visually show how an algorithm works.
Read in an integer number, then determine and display each digit of the number on a
new line.
Algorithm
Line 1: Read Number
Line 2: Digits = ‘ ‘
Line 2: Repeat
Line 3: Remainder = Integer remainder of (Number /10)
Line 4: Number = Number /10 (the integer answer ignoring the decimal value)
Line 5: Digits = String(Remainder) + Digits
Line 6: Until Number = 0
Line 7: Display Digits
Take note
Flowchart
Here is an example of a flowchart for this algorithm:
Trace table
You can also draw the trace table for the flowchart.
IPO Chart
You can also use an Input, Processing and Output (IPO) chart to show exactly what
input, processing and output is needed in your application. The IPO chart below is for
the Isolate Digit algorithm:
Activity A.1
A.1.1 A number is a prime number if it has only 2 factors, the number 1 and the
number itself.
Do the following:
• Create an algorithm to determine whether a number is prime or not.
• Draw the corresponding flowchart for your algorithm.
• Draw an IPO chart for the problem.
• Trace through your flowchart using a value of 6.
Delphi components
EXPLORING DELPHI
COMPONENTS
https://www.youtube.com/watch?
v=912Jh1o1sFA
Example of IPO Chart with components for the Isolate Digit
Algorithm
EVENTS
Delphi is an event-driven programming language. An event is linked to
some code which responds to some action. This action may be
created by user interaction, the system or code logic. An event handler
manages the execution of an event. An example is the OnClick event
for a button.
New words
instantiate – represent as or by an
instant
instance – an example or single
occurrence of something
naming convention – to name
things (generally agreed scheme)
properties – the components or
building blocks
methods – predefined instructions
Activity A.2
A.2.1 Open the GUIComponents_p project located in the Annex – GUI Components
folder.
Modify the form so that it displays as shown below:
In Grade 10 you learnt that variables are used to store information for
later retrieval. You can assign values to variables or read the value
stored in a variable. Study the table below to remind yourself about the
variable types you learnt about.
Table A.3: Variable types
NUMBERS
Numbers are represented by:
Integers (numbers without a decimal point)
Reals (numbers with a decimal point)
https://www.youtube.com/watch?
v=7YqvMLJBb64
If you add, subtract, multiply or divide (/) two real numbers, then the
answer will be a real number.
In the last row of the table above: 5 is included in the real arithmetic
calculation 37.93 / 5 because:
Integers are a subset of real numbers. Every integer can be
represented as a Real
5 can be written as 5.0.
ORDER OF PRECEDENCE
Basic mathematical operators in mathematical expressions are
evaluated using the BODMAS-rule just like you would do when working
in Mathematics. This is known as the order of precedence.
2 + 3 * 26 / (16 – 3)
–5
= 2 + 3 * 26 / 13 – 5 (Level 1 – Brackets)
= 2 + 72 / 13 – 5 (Level 2 –
multiplication)
MATHEMATICAL METHODS
You learnt about the following mathematical methods in Grade 10:
MATH OPERATIONS
https://www.youtube.com/watch?
v=s_PNKJ2x1x4
Note:
To prevent Delphi from generating the same set of random numbers,
you need to place the randomize command at the start of your
application:
Example:
begin
…
Randomize
iNum := Random(20) + 1;
rValue := Random ();
…
end;
This will ensure that each time your application runs, a new set of
random numbers will be generated
New words
first argument – is a string that
holds instructions for formatting
second argument – holds the values
that needs to be converted into a
formatted string
event – an occurrence of something
procedure – an official way of doing
something
function – the operation of
something in a particular way
local variable – variables that have a
local scope
Note:
The format function has two arguments
The first argument ‘%8s%10.2f’ is a string that holds instructions for
formatting. In the control code used:
% symbol indicates that the text which follows is formatting
instructions and not normal text.
There are two formatting instructions in ‘%8s%10.2f’
First formatting instruction %8s: 8 indicates that the string to be
displayed must contain 8 characters.
Second formatting instruction %10.2f’: 10 indicates that the string to
be displayed must contain 10 characters. 2 indicates that the 10
characters must have 2 decimal points.
The s and f indicate the type of data that will be formatted. Data
types are indicated as follows:
memDisplay.Lines.Add(Format('%10s%10.2f',
['value',45.345]));
memDisplay.Lines.Add(Format('%10s%10s%10s',
['Number','Square','Square Root']));
memDisplay.Lines.Add(Format('%10d%10d%10.2f',
[10,Sqr(10),Sqrt(10)]));
SCOPE OF A VARIABLE
Variables can be declared as follows:
At the beginning of the unit; or
They can be declared in an event, procedure or function.
Take note
COMMENT STATEMENTS
Comments are used by programmers to make a program more easier
to read and understand its purpose.
New words
Activity A.3
In every day life you often make decisions to solve a problem. The
same is true for when you write or develop a program – you have to
use the decision-making process regularly. In the decision-making
process, conditions (criteria) are tested. A condition evaluates one of
the two Boolean values: TRUE or FALSE. The outcome of the
condition determines which one of the two paths (the YES/TRUE path
or the NO/FALSE path) will be followed. We say that decision making
causes branching to occur in the normal sequential program flow.
Take note
Branching along TRUE or FALSE
paths.
BOOLEAN EXPRESSIONS
A Boolean expression is an expression that evaluates to TRUE or
FALSE. There are three categories of Boolean expressions:
Boolean variable
Simple Boolean expressions
Compound (complex) Boolean expressions.
BOOLEAN VARIABLES
You can assign a Boolean value to a Boolean variable, for example:
bFound := True;
bValid := False;
In this section we will look at each logical operator in a bit more detail.
Both conditions must evaluate to true for the result to be true. If either
condition1 or condition2 is false, then the result will be false, for
example: if A = 5 and B = 7 then:
GLOBAL AND LOCAL VARIABLES
https://www.youtube.com/watch?
v=LPRLU1_dGJE
OR LOGICAL OPERATOR
The OR operator is used to test two conditions in the format:
(condition1) OR (condition2)
Both conditions must evaluate to false for the result to be false. If either
condition1 or condition2 is true, then the result will be true, for
example: if A = 5 and B = 7 then:
Assume the value of the variables is as follow: Gender = ‘F’, Age = 15 and Sport is
‘Netball’.
= TRUE OR FALSE
= TRUE
IF-THEN STATEMENT
In Delphi, you can use the IF-THEN statement to make decisions. IF
and THEN are keywords in Delphi. The IF-THEN statement executes
the statement/s following the THEN keyword if the condition is true and
skips the execution of these statement/s when the condition is false.
Remember!
If <condition>then
<statement1>;
If <condition>then
begin
<statement1>;
<statement2>;
…
end;
Example A.3
If Gender = 'F' then
begin
iNumGirls := iNumGirls + 1;
lblNumGirls.caption := IntToStr(iNumGirls);
end;
IF-THEN-ELSE STATEMENT
In many situations you may want something to happen if a condition is
met, and something else to happen if the condition is not met. For
example, all Grade 10 learners will go for an excursion, all other
learners will watch a movie. A decision needs to be made on the grade
of a learner to determine which activity they will participate in. In the
condition if the grade is 10 then the learner will go on an excursion,
else the learner will watch a movie.
If <condition>THEN
<statement1>
ELSE
<statement2>;
The THEN and ELSE keywords are not followed by a semicolon
The statement before the ELSE statement does not have a semi-
colon
If more than one statement appears in the THEN or ELSE part, then
the statements must appear in a BEGIN…END block
A single statement does not appear in a BEGIN…END block
If <condition>THEN
begin
<statement1>;
…
<statement4>
End
ELSE
begin
<statement5>;
<statement6>;
…
end;
IF <condition1> THEN
IF <condition2> THEN
<statement1>
ELSE
begin
<statement5>;
<statement6>;
…
end;
Example A.4
Note:
The outer conditional statement (iValue > 0) is tested first. If this
condition is true, the inner conditional statement (iValue < 100) is
tested next.
If the conditional statement (iValue < 100) is true, then the
ShowMessage(‘Number is between 0 and 100’) statement is
executed else the ShowMessage(‘Number is 100 or above’), is
executed.
Example A.5
CASE-STATEMENTS
Another type of decision making structure in Delphi is the CASE-
statement. Instead of using a sequence of cascading IF-THEN-ELSE-IF
for decision making, the CASE-statement provides a tidy way of
dealing with decision making. The cascading IF-THEN-ELSE-IF allows
you to execute a block code among many alternatives. If you are
checking on a value of an ordinal type variable using an IF-THEN-
ELSE-IF, it is better to use the CASE-statement.
Syntax of CASE-statement
CASE <variable>OF
value1 : statement1;
value2 : statement2;
value3 : statement3;
ELSE
statement4;
end;
Notes:
Start with the keyword CASE followed by a <variable>followed by
the keyword OF. There is no semicolon after the OF keyword.
The CASE-statement does not have a begin but has an end.
<variable>represents a variable name. The data type of the variable
can be integer or character.
Different cases:
Value1, Value2 and Value3 refer to the cases against which
<variable>will be compared and must be of the same data type as
<variable>.
Each case is followed by a colon.
The statements following the colon indicates what code must be
executed for that case.
Example for case Value2, Statement2 must be executed.
Again, if more than one statement need to be executed in a case,
it must be in a BEGIN... END block
A case can be represented by:
– An integer : 5
– A character : ‘A’
– Range : 3..5
If the same action is required for more than one case then cases can
be grouped as follows:
Case cLetter Of
'a','e','i','o','u': ShowMessage ('Vowel');
//grouped cases are
//
separated by comma
Else
ShowMessage ('Not a vowel')
End;
IN OPERATOR
You can also test if an element is included in a set of values using the
IN operator. The test returns true if the element is found in the set of
values; otherwise the test returns false.
IN operator Syntax
Element IN [set of Values]
Notes:
Element is the variable that is being tested against the s
Element variable/value can only be an ordinal data type (integer, char
and Boolean). The values in the [set of values] must match the data
type of element
The IN operator checks whether the Element is found in the set [set
of Values]. The set of values appear within square brackets [ ]
Example A.6
Case iGrade of
Example A.7
Var cLetter:char;
….
bFound := cLetter IN ['a','b','c'];
if bFound then
ShowMessage('Letter Valid')
else
ShowMessage('Letter Invalid');
…
Notes
If cLetter has the value ‘a’ then bFound will be true and ‘Letter Valid’ will display.
Remember that ‘a’ is not the same as ‘A’
If cLetter has any other value than ‘a’, ‘b’ or ‘c’ then bFound will be false and
‘Letter Invalid’ will display.
As with CASE-statements, when using the IN operator the set of
values can be:
a range of values (with the minimum and maximum values separated
by two full stops).
individual values (with the values separated by commas).
a combination of a range of values and individual values.
Activity A.4
A.4.1 Open the ClientData_p project in the Annex – Client Data folder. The form is
designed to capture the details of a travel client.
Do the following:
The image component imgPicture must display the Destinations image
found in your Client Data folder. Set the stretch and proportional properties
to true.
Create an OnClick event for the [Display] button to:
Read the name, surname, age, gender, places travelled and
Accommodation type for each client.
A client is classified according to the number of places visited as follows:
Display the name, surname, age, gender, places travelled, Category and
Accommodation type for each client.
Example of sample output
Looping
These three loops generally do the same thing: They repeat a number
of instructions until some condition is met. However, they differ in how
they decide when to start and stop the loops.
FOR-LOOP
The FOR-loop is known as an iteration loop since it runs for a specific
number of iterations. The syntax for the FOR-loop is:
The FOR-loop needs a counter, which will be called iCount in the next
example.
The loop starts with the reserved/keyword word: FOR and the same
line ends with a DO.
After the loop definition line, we have a start-end-block of code, that
will be executed several times.
Counting from a minimum value being 1 (in the example) to a
maximum being 10 (as displayed). For each iteration the loop
increases the counter iCount with one (1). If one more than the
maximum value (11) is reached by the counter, the iteration comes
to an end and the next statement following the loop is executed.
FOR LOOPING
https://www.youtube.com/watch?
v=kYgXRi_m0Ak
Example A.8
New words
Var
iCount : Integer;
begin
for iCount := 1 to 10 do
begin
// execute instruction(s)
end; // increment by 1 (always
1)
end;
Var
iCount : Integer;
begin
for iCount := 10 downto 1 do
begin
// execute instruction(s)
end; // decrement by 1 (always
–1)
end;
REPEAT LOOP
The REPEAT…UNTIL loop has got its control structure at the end of
the loop-block. That means one iteration is always executed before the
condition is tested! The REPEAT…UNTIL loop is called a post-
conditional loop because it checks whether it should continue running
at the end of each loop.
Note:
The REPEAT…UNTIL loop structure does not need a BEGIN and
END line.
The REPEAT marks the begin of the loop and UNTIL marks the end
of the loop.
The statements in the loop body are executed repeatedly until the
condition (a Boolean expression) evaluates to true, that is, the loop
body executes when the condition is false and terminates when the
condition becomes true.
The condition is tested only after the loop body has been executed.
The loop body is executed at least once.
We say that this is an ICT loop. The test control variable is initialised
before the loop. The change takes place within the loop and the test
takes place at the end of the loop.
WHILE-LOOP
The WHILE-loop does not necessarily run a specific number of times.
Instead, the while-loop is a conditional (like the REPEAT) but puts its
condition first before executing the looping block. Only if the condition
is satisfied, the loop body will execute, that is, the loop body executes
while the condition is true and exits the loop when the condition is
false.
New words
Note:
The loop starts with the keyword WHILE followed by the condition
and then the keyword DO
DO is not followed by a semi-colon
The body of the loop appears within a BEGIN … END block
The loop executes while the condition is true and exits the loop once
the condition evaluates to false
The loop condition is tested at the beginning of the loop. If the loop
condition evaluates to false upon entering the loop, then the loop is
not executed at all.
With the use of a simple loop, you can quickly add new items to these
components, as shown by the code snippet below.
lstDisplay.Items[0] := 'Name';
lstRolls.Items[iTotal-2] := IntToStr(iCurrent);
For the high roller application, you will create a bar chart that shows which numbers
occur most frequently when you roll two dice. To create this application:
A.1.1 Create a new folder named High Roller.
A.1.2 Create a new HighRoller_p project and save it in the folder Annex – High
Roller.
A.1.3 Create the following user interface:
• Use labels to display the possible outcome when the two dices are thrown.
• Set the Shape property of TShape shapes to stRectangle and change their
Color property to a colour of your choice.
• Use labels below the TShapes to display how many times a total was
generated.
• Place two ListBoxes next to each other. The first ListBox displays the
possible totals when the two dices are rolled. The second ListBox displays
how many times a particular total was achieved
• Add an EditBox to read the number of times the dices must be thrown
A.1.4 Create an OnActivate event to:
Clear the ListBox lstRolls. The ListBox lstRolls will keep count of the number of
times each total was generated when the two dices were thrown. Initially it
sets all counters to zero. Clears the ListBox. Set the initial counter value of
each total to zero (0). Eleven such counters are set, that is, counters for totals
from 2 to 12 are only possible. The two dices cannot roll a total of 0 or 1.
• It also sets the totals (2 to 12) that can be generated in the ListBox
lstNum.
lstRolls.Items.Clear;
for i := 2 to 12 do
begin
lstRolls.Items.Add('0');
lstnum.Items.Add(IntToStr(i));
end;
• Since you will be using random numbers for the dice and want Delphi to
generate different random numbers each time, you need to use the
Randomize command
• Read the number of times you want to roll both dices from the EditBox
edtNum.
• For 1 to the value read from the edtNum EditBox: Randomly generate two
numbers in the range 1 to 6.
• Calculate the total for both dices and store it in variable iTotal.
• For the calculate total, read its counter from the ListBox lstRolls and
increment by 1 and store the value in iCurrent:
iCurrent := StrToInt(lstRolls.Items[itotal-2])
+ 1;
• Remember that the ListBox displays the first item in position 0. So if iTotal
is 4, then the counter counting the number of times 4 occurs will be
displayed in position 2.
• Set the value of lstRolls[iTotal-2] to the iCurrent value
lstRolls.Items[iTotal-2] := IntToStr(iCurrent);
A.1.6 Save and test your application. Here is an example of sample output:
A.1.7 Use a FOR-loop with a value from 2 to 12 to identify which item in the ListBox
has the largest value and store this value in the iMaxCount variable.
iMaxHeight := frmHighRoller.Height-150;
A.1.9 To calculate the height of the first box, use the following code.
Shape height
Shp1.Height :=
Round((StrToInt(lstRolls.Items[0]) / iMaxCount)
*
iMaxHeight);
• The counter for the first total 2 is stored in position 0 in the lstRolls
ListBox. This value is retrieved and converted to integer.
• Calculate the rounded percentage of the value retrieved in bullet one
divided by the maximum variable iMaxCount . The percentage is rounded
since the height property can only accept an integer value.
• The percentage is then multiplied with the maximum allowed height of the
shapes. Each bar’s height will therefore be equal to a percentage of the
maximum possible height.
A.1.10 Add the same formula to all the other shapes, making sure to update the
index of lstRolls.Items for each shape.
A.1.11 Save and test your application.
Activity A.5
A.5.1 1. Open the IsolateDigits_p project from the Annex – Isolate Digits folder
and do the following:
• Create an OnClick event for the [Isolate Digits – Method 1] button to
isolate the digits of a number. Use the method to isolate digits as shown in
the Guided activity in Unit 1.1 of this chapter. Display the isolated digits in
the order in which they appear in the number on separate lines.
• Create an OnClick event for the [Isolate Digits – Method 2] button to
isolate the digits of a number using an alternate method to the one in
bullet 1. Display the isolated digits in the order in which they appear in the
number on separate lines.
A.5.2 You can generate any Fibonacci sequence given the first and second term. In
a Fibonacci sequence, the third term is generated by summing the previous
two term:
2 5 7 12 19 …
Open FibonacciSequence_p project from the Annex – Fibonacci Sequence
folder and do the following:
• Read in the first two terms from the EditBoxes
• Create an OnClick event for the [Calculate] button to determine how many
terms of the sequence must be added together to give a sum just greater
than 100.
• Display the terms that are used in the summation, the number of terms
used and the sum of the terms.
• Save and run your project.
Strings
Just like there are functions that are useful to perform on numbers,
there are also functions that are specifically useful to perform on
strings. This section will look at how strings can be combined,
compared and manipulated.
COMBINING STRINGS
The syntax to combine strings is straightforward, you simply add all the
strings together:
FORMATTING CHARACTERS
One way to ensure that your spacing is correct when combining
strings is to make use of the tab and newline characters. These
symbols are described in the table below.
Table 4.8: The Tab and Newline characters
To add the two formatting characters to a string, you use the plus
operator to combine their character values (including the hash symbol)
to an existing string. Occasionally, it will be necessary to use more than
one tab character to align texts of different lengths. The only way to
know if you have added the correct number of tab characters is to test
the application and see the result. It should immediately be visible if
you have added the incorrect number of tab characters.
Figure A.3: Incorrect and correct number of tab character
COMPARING STRINGS
Conditional statements can be used to compare two or more strings.
For example:
Note:
The comparison is not affected by length.
The comparison is carried out on a letter by letter basis.
The comparison is case sensitive.
sPassword := 'SuperSecretCode1';
iLength := Length(sPassword); // 16
https://www.youtube.com/watch?
v=t9oszMtEdQs
MANIPULATING STRINGS
Once you know how to scroll through a string, you can use this
technique to manipulate the string. The table below briefly describes
different ways in which strings can be manipulated.
Table A.9: Ways in which strings can be manipulated
You will learn how to replace each of these algorithms with Delphi
functions later this year.
Activity A.6
PROGRAMMING CHARACTERS
VISIBLE CHARACTERS
The 127th character is the DELETE character, which is used when
something needs to be removed or deleted.
append to open an existing file for writing, set the file pointer to the
end of the file and allows you to add data to the file
append to add an empty row to the end of your database table
array is a data structure that store a set values (elements) of the
same type liked to a single variable name
assume supposed to be the case, without proof
method overloading to have more than one method with the same
name
method overloading to have more than one method with the same
name
method signature is the number of arguments and their data type
method signature to name a method and its formal parameters list
methods predefined instructions
N
Trunc to remove or chop off the decimal part of the real number. It
returns an integer after the truncation
You can use the QR codes on these pages to link to online content for
further information on these topics.
Dear Learner
WHAT MOST SCHOOLS DON’T TEACH
Chapter 1
WHAT’S AN ALGORITHM?
Chapter 2
EXPLAINING BINARY NUMBERS
CONVERT DECIMAL TO HEXIDECIMAL
Chapter 3
DELPHI ARRAYS
Chapter 8
CONNECTING TO AN ACCESS DATABASE
WHAT’S AN ALGORITHM?
EXPLORING DELPHI COMPONENTS
LEARNING ABOUT VARIABLES
CONVERTING REAL NUMBERS TO STRINGS
MATH OPERATIONS
GLOBAL AND LOCAL VARIABLES
FOR LOOPING
FOR AND WHILE LOOPS
MANIPULATING STRINGS IN DELPHI
ANNEXURE
Notes
Contents
Cover
Title Page
Copyright Page
Contents
Term 1
Chapter 1: Grade 10 Revision and Mathematical Functions
Introduction
Unit 1.1 Errors, debugging and mathematical methods
Unit 1.2 Mathematical methods
Consolidation activity
Chapter 2: Nested loops
Introduction
Unit 2.1 Nested loops
Unit 2.2 Using nested loops
Unit 2.3 Creating shapes using nested loops
Consolidation activity
Term 2
Chapter 3: Arrays
Introduction
Unit 3.1 Arrays
Unit 3.2 Searching and sorting arrays
Unit 3.3 Parallel arrays
Consolidation activity
Chapter 4: String and date manipulation
Introduction
Unit 4.1 Built-in string methods
Unit 4.2 Delimited strings
Unit 4.3 Built-in Date-Time methods
Consolidation activity
Term 3
Chapter 5: Text files
Introduction
Unit 5.1 Introduction to text files
Unit 5.2 Reading from a text file
Unit 5.3 Writing to a text file
Unit 5.4 Creating reports
Consolidation activity
Chapter 6: User-defined methods
Introduction
Unit 6.1 Introduction to user-defined methods
Unit 6.2 Procedures
Unit 6.3 Functions
Unit 6.4 Basic input validation techniques
Consolidation activity
Chapter 7: User interfaces
Introduction
Unit 7.1 Multi-form user interfaces
Unit 7.2 Dynamic Instantiation of objects
Chapter 8: Databases
Introduction
Unit 8.1 Creating a database
Unit 8.2 Connecting to a database
Unit 8.3 Reading data from a database
Unit 8.4 Writing data to a database
Unit 8.5 Manipulating data
Consolidation activity
Annexure A – Grade 10 Revision
Annexure B – Naming convention of components
Annexure C – Programming and visible characters
Glossary
QR Code list