Skip to content
Book 2: Fundamental Problem-solving and Programming Skills

Book 2 · Chapter 11

Programming

§11.1§11.2§11.3Banker · ≈ 62.6 m · ↘B2·11

This chapter is in the ebook.

Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.

Open in the ebook

For the whole chapter

§11.1 Programming basics

Short code B2·11·1

§11.2 Constructs

Short code B2·11·2

§11.3 Structured programming

Short code B2·11·3

Part A: variables, constants and assignment

Short code B2·11·10

CONSTANT TaxRate = 0.2
DECLARE ItemName : STRING
DECLARE Quantity : INTEGER
DECLARE UnitCost : REAL
DECLARE Total : REAL
ItemName ← "Graph paper"
Quantity ← 4
UnitCost ← 2.5
Total ← Quantity * UnitCost
Total ← Total + Total * TaxRate
OUTPUT Quantity, " x ", ItemName, " = ", Total
Constants first, then one DECLARE per variable, then assignments. Notice that Total is given a value before it is read.

Output

4 x Graph paper = 12
Run and checked before printing
CONSTANT TaxRate = 0.2
DECLARE Total : REAL
Total ← 10.0
TaxRate ← 0.25
OUTPUT Total * TaxRate
A constant cannot be changed while the program runs. The interpreter refuses before anything is output.

Output

ERROR: Line 4: Cannot assign to TaxRate — it is a CONSTANT and never changes
Run and checked before printing
DECLARE Count : INTEGER
Count ← Count + 1
OUTPUT Count
A new variable holds no value at all, not even 0. Reading it before assigning it is an error.

Output

ERROR: Line 2: 'Count' has no value yet (DECLAREd on line 1) — assign it before using it; a variable does not start at 0 or ""
Run and checked before printing

Expressions and operators

Short code B2·11·11

DECLARE A : INTEGER
DECLARE B : INTEGER
A ← 17
B ← 5
OUTPUT A + B * 2
OUTPUT (A + B) * 2
OUTPUT A / B
OUTPUT A DIV B, " remainder ", A MOD B
OUTPUT A > B AND B > 10
OUTPUT NOT (A = B) OR B > 10
Predict each line before you look at the output. / always gives a REAL; DIV and MOD give INTEGERs.

Output

27
44
3.4
3 remainder 2
FALSE
TRUE
Run and checked before printing
DECLARE First : STRING
DECLARE Room : INTEGER
DECLARE Label : STRING
First ← "Hina"
Room ← 12
Label ← First & " - Room " & NUM_TO_STR(Room)
OUTPUT Label
OUTPUT LENGTH(Label)
& joins two STRINGs. A number must become a STRING first: NUM_TO_STR comes from the paper's insert.

Output

Hina - Room 12
14
Run and checked before printing
DECLARE First : STRING
DECLARE Room : INTEGER
DECLARE Label : STRING
First ← "Hina"
Room ← 12
Label ← First & " - Room " & Room
OUTPUT Label
Join a STRING to an INTEGER with & and the program is refused.

Output

ERROR: Line 6: & joins two STRINGs — Room is INTEGER; write NUM_TO_STR(Room), or OUTPUT the values separated by commas
Run and checked before printing

Input and output

Short code B2·11·12

DECLARE Name : STRING
DECLARE Age : INTEGER
OUTPUT "Enter your name"
INPUT Name
OUTPUT "Enter your age"
INPUT Age
OUTPUT "Hello ", Name, ", next year you will be ", Age + 1
A prompt, then INPUT into a variable. Commas in OUTPUT print the values side by side on one line (lines beginning › are what was typed).

Output

Enter your name
› Sana
Enter your age
› 16
Hello Sana, next year you will be 17
Run and checked before printing

Built-in functions and library routines

Short code B2·11·13

DECLARE Code : STRING
DECLARE Weight : REAL
Code ← "lhr-2047"
Weight ← 12.75
OUTPUT LENGTH(Code)
OUTPUT MID(Code, 5, 4)
OUTPUT MID(Code, 1, 3)
OUTPUT RIGHT(Code, 2)
OUTPUT UCASE('l'), LCASE('Q')
OUTPUT INT(Weight)
The guide's own functions at work. Notice that MID(Code, 1, 3) does the job other languages give to a LEFT function.

Output

8
2047
lhr
47
Lq
12
Run and checked before printing
DECLARE Roll : INTEGER
DECLARE Go : INTEGER
DECLARE InRange : BOOLEAN
InRange ← TRUE
FOR Go ← 1 TO 1000
   Roll ← INT(RAND(6)) + 1
   IF Roll < 1 OR Roll > 6 THEN
      InRange ← FALSE
   ENDIF
NEXT Go
OUTPUT "Every roll was from 1 to 6: ", InRange
RAND(6) gives a REAL from 0 up to (not including) 6; INT(…) + 1 turns it into a whole number from 1 to 6. A thousand rolls prove the range.

Output

Every roll was from 1 to 6: TRUE
Run and checked before printing
DECLARE Line : STRING
DECLARE Qty : INTEGER
Line ← "PEN*0036"
Qty ← STR_TO_NUM(MID(Line, 5, 4))
OUTPUT Qty * 2
Text that holds digits is still text: STR_TO_NUM (from the insert) turns "0036" into the number 36.

Output

72
Run and checked before printing
DECLARE FirstName : STRING
DECLARE FamilyName : STRING
DECLARE BirthYear : INTEGER
DECLARE UserName : STRING
OUTPUT "Enter first name"
INPUT FirstName
OUTPUT "Enter family name"
INPUT FamilyName
OUTPUT "Enter year of birth"
INPUT BirthYear
UserName ← MID(FamilyName, 1, 3) & MID(FirstName, 1, 1) & RIGHT(NUM_TO_STR(BirthYear), 2)
OUTPUT UserName
The Mark Ladder's model answer, run with Zara Khan, born 2009.

Output

Enter first name
› Zara
Enter family name
› Khan
Enter year of birth
› 2009
KhaZ09
Run and checked before printing

From a design to pseudocode

Short code B2·11·14

DECLARE Mark : INTEGER
DECLARE Count : INTEGER
DECLARE Total : INTEGER
Count ← 0
Total ← 0
INPUT Mark
WHILE Mark <> -1
   Total ← Total + Mark
   Count ← Count + 1
   INPUT Mark
ENDWHILE
OUTPUT Count, " marks, total ", Total
The flowchart above as pseudocode, run with the marks 12, 7 and 20, then the rogue value −1.

Output

› 12
› 7
› 20
› -1
3 marks, total 39
Run and checked before printing
DECLARE Celsius : REAL
DECLARE Fahrenheit : REAL
OUTPUT "Enter the temperature in Celsius"
INPUT Celsius
Fahrenheit ← Celsius * 9 / 5 + 32
IF Fahrenheit > 100 THEN
   OUTPUT Fahrenheit, " Fever"
ELSE
   OUTPUT Fahrenheit, " Normal"
ENDIF
The table as pseudocode. Input: 38.5.

Output

Enter the temperature in Celsius
› 38.5
101.3 Fever
Run and checked before printing

Part B: selection with IF

Short code B2·11·20

DECLARE Age : INTEGER
DECLARE Student : BOOLEAN
Age ← 17
Student ← TRUE
IF Age < 12 THEN
   OUTPUT "Child ticket"
ELSE
   IF Age >= 60 OR Student = TRUE THEN
      OUTPUT "Concession ticket"
   ELSE
      OUTPUT "Adult ticket"
   ENDIF
ENDIF
A nested IF: the inner IF is only reached when the outer condition is FALSE.

Output

Concession ticket
Run and checked before printing

Output

9 FALSE Child ticket
17 TRUE Concession ticket
35 FALSE Adult ticket
64 FALSE Concession ticket
Run and checked before printing
DECLARE Age : INTEGER
Age ← 70
IF Age < 12 THEN
   OUTPUT "Child ticket"
ELSEIF Age >= 60 THEN
   OUTPUT "Concession ticket"
ENDIF
There is no ELSEIF in Cambridge pseudocode. The interpreter says what to write instead.

Output

ERROR: Line 5: There is no ELSEIF in pseudocode — write ELSE on its own line, then a new IF … THEN … ENDIF inside it (each IF needs its own ENDIF)
Run and checked before printing

CASE

Short code B2·11·21

DECLARE Mark : INTEGER
DECLARE Grade : CHAR
DECLARE Pupil : INTEGER
FOR Pupil ← 1 TO 4
   INPUT Mark
   CASE OF Mark
      70 TO 100 : Grade ← 'A'
      55 TO 69 : Grade ← 'B'
      40 TO 54 : Grade ← 'C'
      OTHERWISE : Grade ← 'U'
   ENDCASE
   OUTPUT "Grade ", Grade
NEXT Pupil
CASE with ranges. The clauses are tested from the top, and OTHERWISE catches everything else. Inputs: 85, 58, 40, 12.

Output

› 85
Grade A
› 58
Grade B
› 40
Grade C
› 12
Grade U
Run and checked before printing
DECLARE Choice : CHAR
OUTPUT "A = Add, D = Delete, Q = Quit"
INPUT Choice
Choice ← UCASE(Choice)
CASE OF Choice
   'A' : OUTPUT "Adding a record"
   'D' : OUTPUT "Deleting a record"
   'Q' : OUTPUT "Goodbye"
   OTHERWISE : OUTPUT "Not a menu option"
ENDCASE
CASE on a CHAR. Convert the input to upper case first, so d and D both match. Input: d.

Output

A = Add, D = Delete, Q = Quit
› d
Deleting a record
Run and checked before printing

Count-controlled loops: FOR

Short code B2·11·22

DECLARE Count : INTEGER
DECLARE Items : INTEGER
FOR Count ← 20 TO 4 STEP -4
   OUTPUT Count
NEXT Count
Items ← 0
FOR Count ← 1 TO Items
   OUTPUT "Never printed"
NEXT Count
OUTPUT "Done"
Predict: how many times does each loop run, and what is output?

Output

20
16
12
8
4
Done
Run and checked before printing
DECLARE Odd : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR Odd ← 1 TO 19 STEP 2
   Total ← Total + Odd
NEXT Odd
OUTPUT "Total: ", Total
A count-controlled loop with STEP 2: the total of the odd numbers from 1 to 19.

Output

Total: 100
Run and checked before printing

Pre-condition loops: WHILE

Short code B2·11·23

Output

20
16
12
8
4
Done
Run and checked before printing
DECLARE Bacteria : INTEGER
DECLARE Limit : INTEGER
DECLARE Hours : INTEGER
INPUT Bacteria
INPUT Limit
Hours ← 0
WHILE Bacteria <= Limit
   Bacteria ← Bacteria * 2
   Hours ← Hours + 1
ENDWHILE
OUTPUT Hours, " hours, ", Bacteria, " bacteria"
A pre-condition loop: the condition is tested before every pass. Inputs: start 300, limit 5000.

Output

› 300
› 5000
5 hours, 9600 bacteria
Run and checked before printing
DECLARE Bacteria : INTEGER
DECLARE Limit : INTEGER
DECLARE Hours : INTEGER
INPUT Bacteria
INPUT Limit
Hours ← 0
WHILE Bacteria <= Limit
   Bacteria ← Bacteria * 2
   Hours ← Hours + 1
ENDWHILE
OUTPUT Hours, " hours, ", Bacteria, " bacteria"
The same program with a start of 6000: the condition is FALSE at the first test, so the body never runs.

Output

› 6000
› 5000
0 hours, 6000 bacteria
Run and checked before printing

Post-condition loops: REPEAT

Short code B2·11·24

DECLARE Mark : INTEGER
REPEAT
   OUTPUT "Enter a mark from 0 to 100"
   INPUT Mark
UNTIL Mark >= 0 AND Mark <= 100
OUTPUT "Accepted: ", Mark
A post-condition loop for validation: the body runs at least once, and repeats until the input is acceptable. Inputs: 120, −5, 73.

Output

Enter a mark from 0 to 100
› 120
Enter a mark from 0 to 100
› -5
Enter a mark from 0 to 100
› 73
Accepted: 73
Run and checked before printing

Choosing the right loop

Short code B2·11·25

DECLARE Reading : INTEGER
DECLARE DryDays : INTEGER
DECLARE Largest : INTEGER
DryDays ← 0
Largest ← 0
INPUT Reading
WHILE Reading <> -1
   IF Reading = 0 THEN
      DryDays ← DryDays + 1
   ENDIF
   IF Reading > Largest THEN
      Largest ← Reading
   ENDIF
   INPUT Reading
ENDWHILE
OUTPUT "Dry days: ", DryDays
OUTPUT "Largest: ", Largest
The Mark Ladder's model answer, run with the rainfall readings 0, 12, 0, 31, 4 and the rogue value −1.

Output

› 0
› 12
› 0
› 31
› 4
› -1
Dry days: 2
Largest: 31
Run and checked before printing

Loops over strings

Short code B2·11·26

DECLARE Word : STRING
Word ← "STAR"
OUTPUT Word[1]
A string is not an array: Word[1] is refused. Pick characters out with MID.

Output

ERROR: Line 3: Word is STRING, not an array — it cannot be indexed with [ ] (use MID / SUBSTRING to pick characters from a string)
Run and checked before printing
DECLARE Word : STRING
DECLARE Index : INTEGER
DECLARE Ch : CHAR
DECLARE Vowels : INTEGER
Word ← "Education"
Vowels ← 0
FOR Index ← 1 TO LENGTH(Word)
   Ch ← MID(Word, Index, 1)
   Ch ← LCASE(Ch)
   IF Ch = 'a' OR Ch = 'e' OR Ch = 'i' OR Ch = 'o' OR Ch = 'u' THEN
      Vowels ← Vowels + 1
   ENDIF
NEXT Index
OUTPUT Vowels, " vowels in ", Word
Visit every character with a FOR loop and MID(Word, Index, 1). Counting vowels in "Education".

Output

5 vowels in Education
Run and checked before printing

Output

4 R R
3 A RA
2 T RAT
1 S RATS
RATS
Run and checked before printing

Part C: procedures

Short code B2·11·30

PROCEDURE Banner(Message : STRING, Width : INTEGER)
   DECLARE Line : STRING
   DECLARE Index : INTEGER
   Line ← ""
   FOR Index ← 1 TO Width
      Line ← Line & "*"
   NEXT Index
   OUTPUT Line
   OUTPUT Message
   OUTPUT Line
ENDPROCEDURE

CALL Banner("Results day", 11)
CALL Banner("Done", 4)
One procedure, two calls with different arguments. The code inside is written once.

Output

***********
Results day
***********
****
Done
****
Run and checked before printing

Functions and RETURN

Short code B2·11·31

FUNCTION IsLeapYear(Year : INTEGER) RETURNS BOOLEAN
   IF Year MOD 400 = 0 THEN
      RETURN TRUE
   ENDIF
   IF Year MOD 100 = 0 THEN
      RETURN FALSE
   ENDIF
   RETURN Year MOD 4 = 0
ENDFUNCTION

DECLARE Days : INTEGER
IF IsLeapYear(2028) THEN
   Days ← 366
ELSE
   Days ← 365
ENDIF
OUTPUT "2028 has ", Days, " days"
OUTPUT "2100 is a leap year: ", IsLeapYear(2100)
A function returns one value, and the call is used inside an expression. It is never used with CALL.

Output

2028 has 366 days
2100 is a leap year: FALSE
Run and checked before printing
FUNCTION Twice(Number : INTEGER) RETURNS INTEGER
   OUTPUT Number * 2
ENDFUNCTION

DECLARE Result : INTEGER
Result ← Twice(4)
OUTPUT Result
OUTPUT in place of RETURN: the function shows a value on the screen but gives nothing back to the caller, so the interpreter refuses it.

Output

ERROR: Line 1: FUNCTION Twice never executes RETURN — a function must RETURN a value of type INTEGER
Run and checked before printing
FUNCTION Twice(Number : INTEGER) RETURNS INTEGER
   RETURN Number * 2
ENDFUNCTION

CALL Twice(4)
CALL is for procedures. A function's value must be used in an expression.

Output

ERROR: Line 5: Twice is a FUNCTION — do not CALL it; use its value in an expression: Result ← Twice(…) (pseudocode guide §8.2)
Run and checked before printing
FUNCTION CountChar(Text : STRING, Target : CHAR) RETURNS INTEGER
   DECLARE Index : INTEGER
   DECLARE Total : INTEGER
   Total ← 0
   FOR Index ← 1 TO LENGTH(Text)
      IF MID(Text, Index, 1) = Target THEN
         Total ← Total + 1
      ENDIF
   NEXT Index
   RETURN Total
ENDFUNCTION

OUTPUT CountChar("banana", 'a')
OUTPUT CountChar("banana", 'z')
OUTPUT CountChar("", 'a')
A function with a loop inside: CountChar returns how many times one character appears. The test harness tries three cases, including an empty string.

Output

3
0
0
Run and checked before printing

Parameters: by value and by reference

Short code B2·11·32

PROCEDURE AddTenByVal(BYVAL Points : INTEGER)
   Points ← Points + 10
   OUTPUT "Inside, by value: ", Points
ENDPROCEDURE

PROCEDURE AddTenByRef(BYREF Points : INTEGER)
   Points ← Points + 10
   OUTPUT "Inside, by reference: ", Points
ENDPROCEDURE

DECLARE Score : INTEGER
Score ← 50
CALL AddTenByVal(Score)
OUTPUT "After the BYVAL call: ", Score
CALL AddTenByRef(Score)
OUTPUT "After the BYREF call: ", Score
By value, the procedure works on a copy; by reference, it works on the caller's own variable.

Output

Inside, by value: 60
After the BYVAL call: 50
Inside, by reference: 60
After the BYREF call: 60
Run and checked before printing
PROCEDURE Order(BYREF Low : INTEGER, High : INTEGER)
   DECLARE Temp : INTEGER
   IF Low > High THEN
      Temp ← Low
      Low ← High
      High ← Temp
   ENDIF
ENDPROCEDURE

DECLARE First : INTEGER
DECLARE Second : INTEGER
First ← 42
Second ← 17
CALL Order(First, Second)
OUTPUT First, " ", Second
BYREF is written once and covers every parameter after it, so High is passed by reference too: both variables are put in order.

Output

17 42
Run and checked before printing
PROCEDURE Order(BYREF Low : INTEGER, BYVAL High : INTEGER)
   DECLARE Temp : INTEGER
   IF Low > High THEN
      Temp ← Low
      Low ← High
      High ← Temp
   ENDIF
ENDPROCEDURE

DECLARE First : INTEGER
DECLARE Second : INTEGER
First ← 42
Second ← 17
CALL Order(First, Second)
OUTPUT First, " ", Second
Write BYVAL in front of High and only Low is shared: First becomes 17, but the swapped 42 goes into a copy and is lost.

Output

17 17
Run and checked before printing
FUNCTION NextNumber(BYREF Counter : INTEGER) RETURNS INTEGER
   Counter ← Counter + 1
   RETURN Counter
ENDFUNCTION

DECLARE Tickets : INTEGER
Tickets ← 1
OUTPUT NextNumber(Tickets)
The guide does not allow a parameter to be passed by reference to a function.

Output

ERROR: Line 1: Parameter Counter cannot be BYREF — parameters should not be passed by reference to a FUNCTION (pseudocode guide §8.3)
Run and checked before printing

Output

before 42 17
enter 42 17
swap 17 42
after 17 42
Run and checked before printing

Local and global variables

Short code B2·11·33

DECLARE Count : INTEGER

PROCEDURE ShowLocal()
   DECLARE Count : INTEGER
   Count ← 99
   OUTPUT "Local Count: ", Count
ENDPROCEDURE

Count ← 5
CALL ShowLocal()
OUTPUT "Global Count: ", Count
Two variables called Count: the local one inside ShowLocal hides the global one, which keeps its value.

Output

Local Count: 99
Global Count: 5
Run and checked before printing
DECLARE Lives : INTEGER

PROCEDURE LoseLife()
   Lives ← Lives - 1
ENDPROCEDURE

Lives ← 3
CALL LoseLife()
CALL LoseLife()
OUTPUT "Lives left: ", Lives
A procedure that changes a global variable has a side effect: the change is visible everywhere, though the call does not show it.

Output

Lives left: 1
Run and checked before printing

Modular design and efficient pseudocode

Short code B2·11·34

DECLARE Stock : ARRAY[1:10] OF INTEGER
DECLARE Index : INTEGER
DECLARE Checks : INTEGER
DECLARE Found : BOOLEAN
FOR Index ← 1 TO 10
   Stock[Index] ← Index * 11
NEXT Index
Checks ← 0
Found ← FALSE
FOR Index ← 1 TO 10
   Checks ← Checks + 1
   IF Stock[Index] = 33 THEN
      Found ← TRUE
   ENDIF
NEXT Index
OUTPUT "FOR loop: ", Checks, " comparisons"
Checks ← 0
Found ← FALSE
Index ← 1
WHILE Found = FALSE AND Index <= 10
   Checks ← Checks + 1
   IF Stock[Index] = 33 THEN
      Found ← TRUE
   ELSE
      Index ← Index + 1
   ENDIF
ENDWHILE
OUTPUT "WHILE loop: ", Checks, " comparisons"
Efficiency: the FOR loop always makes 10 comparisons; the conditional loop stops at the match after 3.

Output

FOR loop: 10 comparisons
WHILE loop: 3 comparisons
Run and checked before printing

Writing a function for the exam

Short code B2·11·35

FUNCTION IsValidCode(Code : STRING) RETURNS BOOLEAN
   DECLARE Index : INTEGER
   DECLARE Ch : CHAR
   DECLARE Valid : BOOLEAN
   IF LENGTH(Code) <> 6 THEN
      RETURN FALSE
   ENDIF
   Valid ← TRUE
   FOR Index ← 1 TO 6
      Ch ← MID(Code, Index, 1)
      IF Index <= 2 THEN
         IF Ch < 'A' OR Ch > 'Z' THEN
            Valid ← FALSE
         ENDIF
      ELSE
         IF Ch < '0' OR Ch > '9' THEN
            Valid ← FALSE
         ENDIF
      ENDIF
   NEXT Index
   RETURN Valid
ENDFUNCTION

OUTPUT "KP0451 ", IsValidCode("KP0451")
OUTPUT "KP045 ", IsValidCode("KP045")
OUTPUT "Kp0451 ", IsValidCode("Kp0451")
OUTPUT "K90451 ", IsValidCode("K90451")
OUTPUT "KP04A1 ", IsValidCode("KP04A1")
OUTPUT "KP04519 ", IsValidCode("KP04519")
The Mark Ladder's model answer, with a test harness: six codes, each chosen to test one rule.

Output

KP0451 TRUE
KP045 FALSE
Kp0451 FALSE
K90451 FALSE
KP04A1 FALSE
KP04519 FALSE
Run and checked before printing

Command-word coach

Short code B2·11·36

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Workbook 2: Programming

Short code W2·11 · Problem-solving and Programming Skills Workbook

The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.

Ask Z about Programming
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook