A pencil-and-paper workbook: think it through first, learn the Delphi, then prove you can do it.
You make decisions all day: Is it raining? Do I have money for a pie? A program does the same, but it can only ask questions with a YES or NO answer. In this unit you will practise decisions on paper before you meet them in Delphi.
| The customer buys… | Offer A (AND) | Offer B (OR) |
|---|---|---|
| Bread and milk | ||
| Bread only | ||
| Milk only | ||
| Nothing |
Lerato decides how to get to school using this flowchart. Follow the arrows and write what she does in each situation.
| Situation | What does Lerato do? |
|---|---|
| Saturday, raining | |
| Monday, sunny | |
| Tuesday, raining, nobody can give her a lift | |
| Wednesday, raining, her aunt can give her a lift |
Draw a flowchart on the grid for this algorithm. Use the correct shapes and label every arrow that leaves a diamond.
Input a mark (iMark). If the mark is 50 or more, then check again: if it is 80 or more display ‘Distinction’, otherwise display ‘Pass’. If the mark is below 50 display ‘Not yet’. Then stop.
Complete the table (T = True, F = False). Work out NOT A first; then use it for the last column.
| A | B | A AND B | A OR B | NOT A | (NOT A) AND B |
|---|---|---|---|---|---|
| T | T | ||||
| T | F | ||||
| F | T | ||||
| F | F |
Thabo is 16 years old (iAge = 16), has R18 (rMoney = 18) and it is break (bBreak = True). Circle True or False for each condition.
| 1 | (iAge >= 14) AND (rMoney >= 20) | True False |
| 2 | (iAge >= 14) OR (rMoney >= 20) | True False |
| 3 | NOT bBreak | True False |
| 4 | (rMoney > 10) AND (NOT bBreak) | True False |
| 5 | (iAge = 15) OR bBreak | True False |
| 6 | NOT ((iAge < 18) AND (rMoney > 100)) | True False |
In Term 1 you used a simple IF. Now you will give the program two paths (IF…ELSE), put decisions inside decisions, and learn why the order of your tests matters.
if iMark >= 50 then begin // two statements: begin ... end lblResult.Caption := 'Pass'; btnCertificate.Enabled := True; end // NO semicolon before else else lblResult.Caption := 'Not yet'; // one statement: no begin needed
// a chain: the order of the tests matters
if iMark >= 80 then
sResult := 'Distinction'
else
if iMark >= 50 then
sResult := 'Pass'
else
sResult := 'Not yet';
// a second question is only asked when the first is True
if bRegistered then
begin
if rFine = 0 then
sMsg := 'You may borrow'
else
sMsg := 'Pay your fine first';
end
else
sMsg := 'Please register';A pie costs less when you buy more. Complete the table for each value of iPies. Write Yes or No for each test, or a dash (-) if the test is never reached.
if iPies >= 10 then
rPrice := 11
else
if iPies >= 5 then
rPrice := 12
else
rPrice := 14;
rTotal := iPies * rPrice;| iPies | iPies >= 10 ? | iPies >= 5 ? | rPrice | rTotal |
|---|---|---|---|---|
| 3 | ||||
| 5 | ||||
| 10 | ||||
| 12 |
A does not compile: find two errors. B compiles, but a learner who scores 50 should pass and only a passing learner may see the certificate button: find two errors. Write the corrected code.
// A if iAge >= 18 lblStatus.Caption := 'Adult'; else lblStatus.Caption := 'Learner'; // B if rMark > 50 then lblResult.Caption := 'Pass' else lblResult.Caption := 'Not yet'; btnCertificate.Visible := True;
A taxi charges R10 for a child under 12, R12 for a pensioner (60 or older) and R20 for everyone else. The age is in the spin edit sedAge. Write the code to work out iFare and show it in lblFare as, for example, R20.
The symbol should be A for 70 or more, B for 50 to 69, C for 30 to 49 and D below 30. The code is meant to do that. What symbol does it give for marks of 75, 55 and 20? Then rewrite the tests so that it works.
if iMark >= 30 then
sSymbol := 'C'
else
if iMark >= 50 then
sSymbol := 'B'
else
if iMark >= 70 then
sSymbol := 'A'
else
sSymbol := 'D';A learner may borrow a book only if registered (checkbox chkRegistered). If registered, check the fine typed in edtFine (a real number): a fine of 0 shows You may borrow a book in lblMsg, otherwise Please pay your fine first. A learner who is not registered sees Please register first. Use a nested IF.
Real rules usually have more than one part: “older than 14 and has permission”. In this unit you will combine conditions in Delphi, use brackets so they mean what you intend, and meet the IN operator.
// WRONG, does not compile: if iAge >= 14 and iAge <= 19 then
if (iAge >= 14) and (iAge <= 19) then
ShowMessage('Teenager');
if (bPaid) or (bSRC) then
ShowMessage('Entry allowed');
if not (iMark >= 50) then // same as iMark < 50
ShowMessage('Not yet');
bResult := bA or bB and bC; // means bA or (bB and bC)
bResult := (bA or bB) and bC; // a different question!if cLetter in ['A', 'E', 'I', 'O', 'U'] then
ShowMessage('Vowel');
if iMonth in [6..8] then // June to August
ShowMessage('Winter');
if not (iSeat in [1..15, 40..55]) then
ShowMessage('Seat must be 1-15 or 40-55');A learner may go on the trip if they have paid and have a permission slip and are not on detention: (bPaid AND bPermission) AND (NOT bDetention). Complete the table (T = True, F = False).
| bPaid | bPermission | bDetention | NOT bDetention | May go? |
|---|---|---|---|---|
| T | T | T | ||
| T | T | F | ||
| T | F | T | ||
| T | F | F | ||
| F | T | T | ||
| F | T | F | ||
| F | F | T | ||
| F | F | F |
Work out the value of each Boolean. Then say in one sentence why they are different.
bA := True; bB := False; bC := False; bResult1 := bA or bB and bC; bResult2 := (bA or bB) and bC;
Use iMark = 62, cGrade = 'C', bPaid = True and iDay = 6. Circle True or False for each condition.
| 1 | (iMark >= 50) AND bPaid | True False |
| 2 | (iMark IN [40..59]) OR (cGrade = 'B') | True False |
| 3 | cGrade IN ['A'..'C'] | True False |
| 4 | NOT bPaid | True False |
| 5 | NOT (iDay IN [1..5]) | True False |
| 6 | (iMark < 50) OR NOT bPaid | True False |
Each condition has a mistake. Say what is wrong and write it correctly.
1. if iAge >= 14 and iAge <= 19 then 2. if cLetter = 'A' or 'E' or 'I' then 3. if not iMark >= 50 then
Write a Delphi condition (the part between if and then) for each sentence.
(a) The age iAge is from 14 to 16, including both.
(b) Entry is free if iAge is under 6 or 60 and over.
(c) The grade iGrade is not 8, 9 or 10.
(d) The character cKey is a digit from 0 to 9.
A ticket costs R150. Only Grade 11 and 12 learners may buy one (the grade is in the spin edit sedGrade). A learner gets R30 off if they paid early (chkEarly is checked) or are on the SRC (chkSRC is checked). Show the price in lblPrice as R120. A learner in any other grade sees Not eligible in the label. Use an integer variable iPrice.
When one value can lead to many different outcomes, a long IF chain gets untidy. CASE is the neat alternative. You will also learn to ask the user a Yes/No question with MessageDlg.
| A passenger travels to zone… | Fare |
|---|---|
| 2 | |
| 6 | |
| 7 |
case iZone of 1 : iFare := 12; 2, 3 : iFare := 18; 4..6 : iFare := 25; else iFare := 40; end;
Circle the better tool for each job.
| 1 | Turn a mark from 0 to 100 into a symbol from 1 to 7. | IF CASE |
| 2 | Check that the learner is 14 or older and has paid. | IF CASE |
| 3 | Turn the day number 1 to 7 into a day name. | IF CASE |
| 4 | Decide whether a real-number price is above R100. | IF CASE |
| 5 | Choose the taxi fare from the zone number. | IF CASE |
| 6 | Check whether the text in edtName is the word Admin. | IF CASE |
Use the CASE statement in Learn It. For each zone, write which line matches (1, 2, 3, 4..6 or else) and the value of iFare.
case iZone of 1 : iFare := 12; 2, 3 : iFare := 18; 4..6 : iFare := 25; else iFare := 40; end;
| iZone | Line that matches | iFare |
|---|---|---|
| 1 | ||
| 3 | ||
| 4 | ||
| 7 |
What is the value of sGroup after the code runs when cLetter is 'M'? What if it is 'Z'? What if it is the lowercase 'c'? (Capital letters come before lowercase letters in the alphabet of the computer.)
case cLetter of 'A'..'F' : sGroup := 'Group 1'; 'G'..'L' : sGroup := 'Group 2'; 'M'..'R' : sGroup := 'Group 3'; else sGroup := 'Group 4'; end;
This code should say whether iDay (1 = Monday … 7 = Sunday) is a school day, a weekend day or invalid. It does not compile. Find two errors.
case iDay of 1..5 : sType := 'School day'; 5..7 : sType := 'Weekend'; else sType := 'Invalid day';
if MessageDlg('Delete all the entries?', mtConfirmation, mbYesNo, 0) = mrYes then
memOut.Clear
else
ShowMessage('Nothing was deleted');The mark is in iMark (0 to 100). Use a CASE statement to put the symbol in sSymbol: 80–100 is 7, 70–79 is 6, 60–69 is 5, 50–59 is 4, 40–49 is 3, 30–39 is 2 and below 30 is 1.
When the user clicks btnExit, ask Do you really want to quit? with a question icon and Yes/No buttons. If the answer is Yes, close the form with Close. Otherwise show Welcome back! with ShowMessage.
Programs must cope with users who type spaces, capitals and nonsense. Here you will measure and tidy text, check data before you use it, and decide when set-up code should run.
A learner typed a name with a space before and after it. The word below is stored in sName and every box is one character (the empty boxes are spaces). (a) How many characters are there in all (Length)? (b) What would Trim leave, and what is its length? (c) Write the result of UpperCase applied to the trimmed name.
| Field | What the learner wrote |
|---|---|
| Name | (left blank) |
| Grade | 17 |
| Cell number (10 digits) | 082 55 |
sName := Trim(edtName.Text); // ' aya ' becomes 'aya' iLen := Length(sName); // 3 sBig := UpperCase(sName); // 'AYA' cFirst := UpCase(sName[1]); // 'A' (one Char, so UpCase) sName := UpperCase(Trim(edtName.Text)); // functions can be nested
sName holds ' Zanele Mkhize ', which starts with two spaces and ends with one. Write the result of each expression. Put text answers in single quotes.
| Expression | Result |
|---|---|
| Length(sName) | |
| Trim(sName) | |
| Length(Trim(sName)) | |
| UpperCase(Trim(sName)) | |
| UpCase(sName[4]) |
rNum := StrToFloat(edtNum.Text);
if rNum < 0 then
ShowMessage('You cannot take the square root of a negative number')
else
lblRoot.Caption := FloatToStrF(Sqrt(rNum), ffFixed, 8, 2);
if Trim(edtName.Text) = '' then
begin
ShowMessage('Please type your name');
Exit; // stop here, do nothing else
end;A ticket costs R45. The rule says between 1 and 6 tickets may be ordered. Complete the table for each value typed.
iQty := StrToInt(edtQty.Text); if (iQty < 1) or (iQty > 6) then sMsg := 'Invalid' else sMsg := 'Total R' + IntToStr(iQty * 45);
| iQty | iQty < 1 | iQty > 6 | sMsg |
|---|---|---|---|
| 0 | |||
| 6 | |||
| 7 | |||
| 3 |
This code should greet the learner by name and show the first letter in capitals. Find three errors and rewrite the code correctly.
sName := Trim(edtName.Text);
if sName = 0 then
ShowMessage('Please type your name');
cInitial := UpperCase(sName[1]);
lblHi.Caption := 'Hello ' + sName + ', your initial is ' + cInitial;The learner types a number in edtNum and clicks the button to get the square root in lblRoot. Write the code so the program does not crash when the number is negative: show the message Negative numbers have no square root instead.
procedure TForm1.FormCreate(Sender: TObject); begin Randomize; // once only lblResult.Caption := ''; btnCalc.Enabled := False; end; procedure TForm1.FormActivate(Sender: TObject); begin edtName.SetFocus; // every time the form is activated end;
Which event is the better place for each job?
| 1 | Call Randomize once when the program starts. | FormCreate FormActivate |
| 2 | Put the cursor in edtName each time the user returns to the form. | FormCreate FormActivate |
| 3 | Set lblResult to an empty string when the program opens. | FormCreate FormActivate |
| 4 | Refresh the “last visited” label each time the form comes to the front. | FormCreate FormActivate |
No program runs alone. It runs on hardware, and today most computers are linked together. This theory unit uses diagrams and classification, with no computer needed.
Circle the category for each device.
| 1 | Scanner | Input Output Storage |
| 2 | Data projector | Input Output Storage |
| 3 | Solid state drive (SSD) | Input Output Storage |
| 4 | Microphone | Input Output Storage |
| 5 | Speakers | Input Output Storage |
| 6 | Memory card | Input Output Storage |
| 7 | Barcode scanner at the till | Input Output Storage |
| 8 | Printer | Input Output Storage |
Write the name of the part: motherboard, CPU, RAM or storage.
| Job | Which part? (write the name) |
|---|---|
| Carries out program instructions; the “brain” | |
| The main circuit board that joins all the parts together | |
| Temporary workspace that is wiped when the power is off | |
| Keeps your files when the computer is switched off |
Write what each port is used for.
| Port | Used for |
|---|---|
| USB | |
| HDMI | |
| Network (NIC) port | |
| VGA |
Circle the best answer.
| 1 | A smartwatch linked to your phone by Bluetooth | PAN HAN LAN WAN |
| 2 | The Wi-Fi at your house connecting the family's phones and the smart TV | PAN HAN LAN WAN |
| 3 | The computer lab at your school | PAN HAN LAN WAN |
| 4 | A bank's ATMs and branches across South Africa | PAN HAN LAN WAN |
| 5 | Two buildings on the same school campus joined by a cable | PAN HAN LAN WAN |
| 6 | The Internet | PAN HAN LAN WAN |
Circle the type that fits each description.
| 1 | A school computer lab where one server controls all log-ins | Client-server Peer-to-peer |
| 2 | Two friends share files between their laptops at home | Client-server Peer-to-peer |
| 3 | One administrator manages every user account and the backups | Client-server Peer-to-peer |
| 4 | Every computer has equal status and there is no central computer | Client-server Peer-to-peer |
| 5 | If one computer fails, everybody loses access to the shared files | Client-server Peer-to-peer |
Draw a star network for a small computer lab on the blank page below. Show: 5 PCs (one is the teacher's), a server, a printer, a switch in the middle, and a router linking the switch to the Internet. Label every device. Under the drawing write what type of network the lab is (PAN, HAN, LAN or WAN) and whether it is client-server or peer-to-peer.
A spaza shop owner has three computers (the till, an office laptop and a tablet) and one printer. She asks you whether she needs a server. Recommend client-server or peer-to-peer and give two reasons.
No notes, no computer. Show all your working. Write Delphi code neatly and use correct indentation.
A school fun run charges an entry fee. Trace the code for each runner. Write the value of iFee after the age tests, and the final iFee after the member discount.
if iAge < 6 then
iFee := 0
else
if iAge <= 17 then
iFee := 30
else
iFee := 60;
if bMember and (iFee > 0) then
iFee := iFee - 10;| iAge | bMember | iFee after age tests | Final iFee |
|---|---|---|---|
| 4 | True | ||
| 12 | False | ||
| 17 | True |
What appears in lblOut?
sTxt := ' Load shedding '; sTxt := Trim(sTxt); iLen := Length(sTxt); sTxt := UpperCase(sTxt); lblOut.Caption := IntToStr(iLen) + ' ' + sTxt;
Write the value of sSize after the code runs for iPies = 0, for iPies = 4 and for iPies = 9.
case iPies of 0 : sSize := 'None'; 1, 2 : sSize := 'Small'; 3..5 : sSize := 'Medium'; else sSize := 'Big'; end;
Complete the truth table.
| A | B | (NOT A) OR B |
|---|---|---|
| T | T | |
| T | F | |
| F | T | |
| F | F |
Circle PAN, HAN, LAN or WAN for each.
| 1 | Wireless earphones paired with a phone | PAN HAN LAN WAN |
| 2 | The network that links all computers in the school lab | PAN HAN LAN WAN |
| 3 | The network that links a cellphone company's towers across the country | PAN HAN LAN WAN |
Circle Input, Output or Storage for each device.
| 1 | Webcam | Input Output Storage |
| 2 | Flash drive | Input Output Storage |
| 3 | Monitor | Input Output Storage |
Circle the network type described.
| 1 | All the computers have equal status and there is no central server. | Client-server Peer-to-peer |
| 2 | A central computer controls log-ins and the printer. | Client-server Peer-to-peer |
Find two errors and write the corrected code.
if iMark >= 0 and iMark <= 100 then lblOk.Caption := 'Valid'; else lblOk.Caption := 'Invalid';
Find two errors in this CASE statement.
case iMark of 0..50 : sResult := 'Fail'; 50..100 : sResult := 'Pass'; else sResult := 'Invalid';
A quiz mark out of 20 is in the spin edit sedScore. If the score is below 0 or above 20 show Invalid score with ShowMessage and stop. Otherwise use a CASE statement to put a medal in lblMedal: 18 to 20 Gold, 15 to 17 Silver, 10 to 14 Bronze, anything lower Keep trying.
The learner types a name in edtName. Trim it. If it is empty show Please enter a name with ShowMessage. Otherwise display Hello, followed by the name in capitals in lblWelcome and the number of characters in the name in lblLen.
When btnClear is clicked, ask Delete this record? with a confirmation icon and Yes/No buttons. If the user clicks Yes clear memOut and show Cleared with ShowMessage. (Write the whole event handler.)
Write one IF statement (the whole statement) that shows Free entry in lblEntry when iAge is under 6 or is 60 and over, and Pay at the gate otherwise.