Grade 10 — Programming Recap

Data types · operators · functions · decisions · loops · strings — everything on one page.

Delphi · Paper 1

Data, Variables & Input/Output

Data types

IntegerWhole number — age, count, mark
RealDecimal — price, average
StringText — name, surname, ID
CharOne character — a grade symbol
BooleanTrue or False

Declaring

var iAge : Integer; rPrice : Real; sName : String; bPass : Boolean;
Prefix tip: i = integer, r = real, s = string, b = boolean, c = char.

Conversions

StrToInt(s)Text → Integer
StrToFloat(s)Text → Real
IntToStr(n)Integer → Text
FloatToStr(r)Real → Text
Val(s,n,code)Safe convert; code = 0 if OK
Why convert? An Edit box's .Text is always a String — convert it before doing maths.

Reading input

From an Edit box
iAge := StrToInt(edtAge.Text);
From a SpinEdit
iQty := sedQty.Value;
From a pop-up box
sName := InputBox('Name','Enter:','');
CheckBox / RadioGroup
if chkVip.Checked then ... i := rgpSize.ItemIndex;

Showing output

In a Label
lblOut.Caption := 'Total: ' + IntToStr(iTot);
Pop-up message
ShowMessage('Done!');
Line in a Memo / RichEdit
redOut.Lines.Add(sLine); redOut.Lines.Clear; // clear first
Always clear the output area before adding new results.

Operators & Functions

Operators

+   −   *Add, subtract, multiply
/Real division → Real answer
DIVInteger division (whole part)
MODRemainder only
=   <>   <   >   <=   >=Comparison (relational)
AND   OR   NOTLogical / Boolean
x IN ['a'..'b']Membership test (chars must be quoted)
17 DIV 5 = 3  ·  17 MOD 5 = 2. DIV and MOD work on integers only.

Maths functions

Sqr(x)x squared
Sqrt(x)Square root of x
Round(x)Nearest whole number
Trunc(x)Drop the decimal part
Abs(x)Always positive
Random(n)0 to n−1 (add offset)
Random tip: dice = Random(6) + 1. Call Randomize; once at start.

Char functions

Ord(c)ASCII value of a character
Chr(n)Character from ASCII value
UpCase(c)One char to uppercase
c IN ['A'..'Z']Is it a capital letter?
c IN ['0'..'9']Is it a digit?
Ord('A') // = 65 Chr(66) // = 'B'

Order of operations (BODMAS)

1( )Brackets first
2Sqr SqrtOrders / powers
3* / DIV MODLeft to right
4NOTBoolean negation
5ANDSame level as * /
6+ − ORSame level, left to right
Tip: put brackets around each condition when combining with AND / OR.

Decisions & Loops

Selection

IF…THEN — one path
if iMark >= 50 then lblOut.Caption := 'Pass';
IF…THEN…ELSE — two paths
if iMark >= 50 then sResult := 'Pass' else sResult := 'Fail';
CASE — many fixed choices
case iDay of 1: sName := 'Mon'; 2: sName := 'Tue'; else sName := '?'; end;
Rule: CASE for exact values · IF for ranges and comparisons.

Loops — choose the right one

FOR  known number of times
for i := 1 to 10 do redOut.Lines.Add(IntToStr(i));
FOR…DOWNTO  count backwards
for i := 10 downto 1 do ...
WHILE  may run zero times (check first)
while iNum <= 100 do begin iSum := iSum + iNum; Inc(iNum); end;
REPEAT  runs at least once (check last)
repeat iNum := iNum + 1; until iNum = 5;

String Handling

String functions

Length(s)Number of characters
Copy(s,pos,len)Extract part of a string
Pos(sub,s)Position of sub; 0 if not found
Delete(s,pos,len)Remove characters (in place)
Insert(sub,s,pos)Insert text at a position
UpperCase(s)ALL CAPITALS
LowerCase(s)all lowercase
Trim(s)Remove leading/trailing spaces
s[i]Character at position i (starts at 1)
Position 1, not 0: in Delphi the first character of a string is s[1].

Common string patterns

First / last character
s[1] s[Length(s)]
Is the box empty?
if s = '' then ...
Does it contain something?
if Pos('@', sEmail) > 0 then ...
Count vowels in a loop
for i := 1 to Length(s) do if s[i] in ['a','e','i','o','u'] then Inc(iCount);
Fair comparison: LowerCase both strings before comparing so 'Yes' = 'yes'.

Formatting & Common Errors

Formatting output

FloatToStrF(x,ffFixed,8,2)2 decimal places
FloatToStrF(x,ffCurrency,8,2)R prefix, 2 decimals
FormatDateTime('dd/mm/yyyy',d)Format a date
IntToStr(x)Integer as text
#9Tab — line columns up neatly
lblTot.Caption := FloatToStrF(rTot, ffCurrency, 8, 2); // e.g. R149.90

Common errors & fixes

Undeclared identifierCheck spelling of variable / component
Incompatible typesConvert before assigning (StrToInt…)
EConvertErrorStrToInt failed on text — use Val
Operator not applicableDIV / MOD on a Real — use integers
Division by zeroCheck the divisor isn't 0 first
Missing ; or endCheck semicolons and begin…end pairs
Validate first: check the input box isn't empty and is a number before you calculate.