Skip to content
Book 6: Algorithms, Programming and Logic

Book 6 · Chapter 8

Programming

§8.1§8.2§8.3Banker · ≈ 47.2 m · →B6·8

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

§8.1 Programming concepts · Totalling, counting and string handling (length, substring, upper, lower); arithmetic, relational and logical operators; nested statements · Procedures, functions and parameters; local and global variables; library routines (MOD, DIV, ROUND, RANDOM); writing maintainable programs

Short code B6·8·1

§8.2 Arrays

Short code B6·8·2

§8.3 File handling

Short code B6·8·3

Variables, constants and data types

Short code B6·8·10

DECLARE Lives : INTEGER
DECLARE Speed : REAL
DECLARE Grade : CHAR
DECLARE Player : STRING
DECLARE GameOver : BOOLEAN
Lives ← 3
Speed ← 2.5
Grade ← 'B'
Player ← "Zara"
GameOver ← FALSE
OUTPUT Player, " has ", Lives, " lives"
OUTPUT "Speed: ", Speed, "  Grade: ", Grade
OUTPUT "Game over? ", GameOver
One variable of each of the five data types. Each DECLARE names the variable and its type; each value is a literal of that type.

Output

Zara has 3 lives
Speed: 2.5  Grade: B
Game over? FALSE
Run and checked before printing

Input, output and sequence

Short code B6·8·11

CONSTANT AdultPrice ← 8.50
CONSTANT ChildPrice ← 5.00
DECLARE Children : INTEGER
DECLARE Cost : REAL
OUTPUT "How many children?"
INPUT Children
Cost ← AdultPrice + Children * ChildPrice
OUTPUT "Total for one adult and ", Children, " children: ", Cost
Two constants, one input and one calculation, in sequence. Lines beginning › are the values typed in.

Output

How many children?
› 3
Total for one adult and 3 children: 23.5
Run and checked before printing
DECLARE Left : INTEGER
DECLARE Right : INTEGER
Left ← 4
Right ← 9
Left ← Right
Right ← Left
OUTPUT Left, " ", Right
Predict: this is meant to swap the two values. What does it output?
Run and checked before printing

Selection with IF

Short code B6·8·12

DECLARE Left : INTEGER
DECLARE Right : INTEGER
DECLARE Temp : INTEGER
Left ← 4
Right ← 9
Temp ← Left
Left ← Right
Right ← Temp
OUTPUT Left, " ", Right
The swap done properly: the first value is saved in Temp before it is overwritten.

Output

9 4
Run and checked before printing
DECLARE Mark : INTEGER
OUTPUT "Enter the mark (0 to 100)"
INPUT Mark
IF Mark >= 70
  THEN
    OUTPUT "Distinction"
  ELSE
    IF Mark >= 50
      THEN
        OUTPUT "Pass"
      ELSE
        OUTPUT "Not yet"
    ENDIF
ENDIF
A nested IF chooses one of three grades. Run with a mark of 64.

Output

Enter the mark (0 to 100)
› 64
Pass
Run and checked before printing

Selection with CASE

Short code B6·8·13

DECLARE Size : CHAR
DECLARE Cost : REAL
OUTPUT "Cup size? S, M or L"
INPUT Size
CASE OF Size
  'S' : Cost ← 1.20
  'M' : Cost ← 1.80
  'L' : Cost ← 2.40
  OTHERWISE Cost ← 0.0
ENDCASE
IF Cost = 0.0
  THEN
    OUTPUT "Unknown size"
  ELSE
    OUTPUT "Cost: ", Cost
ENDIF
A CASE statement picks the cost for a cup size. OTHERWISE catches every other character.

Output

Cup size? S, M or L
› M
Cost: 1.8
Run and checked before printing
print("Cup size? S, M or L")
Size = input()
if Size == "S":
    Cost = 1.20
elif Size == "M":
    Cost = 1.80
elif Size == "L":
    Cost = 2.40
else:
    Cost = 0.0
if Cost == 0.0:
    print("Unknown size")
else:
    print("Cost:", Cost)
The cup-size program in Python, VB.NET and Java, given the input M. Python has no CASE, so it uses if … elif … else; VB.NET uses Select Case and Java switch.

Output

Cup size? S, M or L
Cost: 1.8
Run and checked before printing

Iteration: three kinds of loop

Short code B6·8·14

DECLARE Count : INTEGER
FOR Count ← 10 TO 0 STEP -2
    OUTPUT Count
NEXT Count
OUTPUT "Lift off!"
A count-controlled loop with STEP. The counter goes down by 2 each time, so the loop runs six times.

Output

10
8
6
4
2
0
Lift off!
Run and checked before printing
DECLARE Savings : REAL
DECLARE Years : INTEGER
Savings ← 100.0
Years ← 0
WHILE Savings < 200.0 DO
    Savings ← Savings * 1.1
    Years ← Years + 1
ENDWHILE
OUTPUT "Doubled after ", Years, " years"
A pre-condition loop: the test comes first, so if the savings started at 200 or more the body would never run.

Output

Doubled after 8 years
Run and checked before printing
CONSTANT Secret ← 7
DECLARE Guess : INTEGER
DECLARE Tries : INTEGER
Tries ← 0
REPEAT
    OUTPUT "Guess a number from 1 to 10"
    INPUT Guess
    Tries ← Tries + 1
UNTIL Guess = Secret
OUTPUT "Got it in ", Tries, " tries"
A post-condition loop: the body runs before the test, so the player always guesses at least once.

Output

Guess a number from 1 to 10
› 3
Guess a number from 1 to 10
› 9
Guess a number from 1 to 10
› 7
Got it in 3 tries
Run and checked before printing

Totalling and counting in programs

Short code B6·8·15

DECLARE Litres : REAL
DECLARE Total : REAL
DECLARE Days : INTEGER
DECLARE HighDays : INTEGER
Total ← 0.0
Days ← 0
HighDays ← 0
OUTPUT "Litres used today? (-1 to stop)"
INPUT Litres
WHILE Litres <> -1 DO
    Total ← Total + Litres
    Days ← Days + 1
    IF Litres > 150
      THEN
        HighDays ← HighDays + 1
    ENDIF
    OUTPUT "Litres used today? (-1 to stop)"
    INPUT Litres
ENDWHILE
OUTPUT "Days: ", Days, "  Total: ", Total
OUTPUT "Days over 150 litres: ", HighDays
OUTPUT "Average: ", Total / Days
Totalling and counting in one loop: a total, a count of every day, and a count of only the days that pass a test.

Output

Litres used today? (-1 to stop)
› 120
Litres used today? (-1 to stop)
› 165.5
Litres used today? (-1 to stop)
› 140
Litres used today? (-1 to stop)
› 171
Litres used today? (-1 to stop)
› -1
Days: 4  Total: 596.5
Days over 150 litres: 2
Average: 149.125
Run and checked before printing

Arithmetic, relational and logical operators

Short code B6·8·16

DECLARE Minutes : INTEGER
DECLARE Age : INTEGER
DECLARE IsTeen : BOOLEAN
Minutes ← 135
OUTPUT DIV(Minutes, 60), " h ", MOD(Minutes, 60), " min"
OUTPUT 7 / 2, "  ", DIV(7, 2), "  ", MOD(7, 2), "  ", 2 ^ 5
OUTPUT 3 + 4 * 2, "  ", (3 + 4) * 2
Age ← 15
IsTeen ← Age >= 13 AND Age <= 19
OUTPUT "Teenager? ", IsTeen
OUTPUT "Not a teenager? ", NOT IsTeen
Arithmetic, relational and logical operators. A comparison gives a BOOLEAN value, which can be stored or output.

Output

2 h 15 min
3.5  3  1  32
11  14
Teenager? TRUE
Not a teenager? FALSE
Run and checked before printing

String handling

Short code B6·8·17

DECLARE Subject : STRING
Subject ← "Computer Science"
OUTPUT LENGTH(Subject)
OUTPUT UCASE(Subject)
OUTPUT LCASE(Subject)
OUTPUT SUBSTRING(Subject, 10, 7)
OUTPUT SUBSTRING(Subject, 1, 3) & SUBSTRING(Subject, 10, 3)
The four string routines on one string. Positions count from 1, and a space is a character too.

Output

16
COMPUTER SCIENCE
computer science
Science
ComSci
Run and checked before printing
DECLARE Word : STRING
DECLARE Letter : STRING
DECLARE Count : INTEGER
DECLARE Position : INTEGER
Word ← "Avocado"
Count ← 0
FOR Position ← 1 TO LENGTH(Word)
    Letter ← LCASE(SUBSTRING(Word, Position, 1))
    IF Letter = "a"
      THEN
        Count ← Count + 1
    ENDIF
NEXT Position
OUTPUT "Letter a: ", Count
The traced program, run.

Output

Letter a: 2
Run and checked before printing
Word = "Avocado"
Count = 0
for Position in range(len(Word)):
    Letter = Word[Position].lower()
    if Letter == "a":
        Count = Count + 1
print("Letter a:", Count)
The traced program in Python, VB.NET and Java. These languages count string positions from 0, so the loop runs from 0 to one less than the length.

Output

Letter a: 2
Run and checked before printing

Nested statements

Short code B6·8·18

DECLARE Row : INTEGER
DECLARE Col : INTEGER
DECLARE Pattern : STRING
FOR Row ← 1 TO 2
    Pattern ← ""
    FOR Col ← 1 TO 3
        IF MOD(Row * Col, 2) = 0
          THEN
            Pattern ← Pattern & "#"
          ELSE
            Pattern ← Pattern & "."
        ENDIF
    NEXT Col
    OUTPUT Pattern
NEXT Row
The traced program, run: three levels of nesting (FOR, FOR, IF).

Output

.#.
###
Run and checked before printing
for Row in range(1, 3):
    Pattern = ""
    for Col in range(1, 4):
        if (Row * Col) % 2 == 0:
            Pattern = Pattern + "#"
        else:
            Pattern = Pattern + "."
    print(Pattern)
The nested program in Python, VB.NET and Java. % is the remainder operator in all three, the same job as MOD.

Output

.#.
###
Run and checked before printing

Library routines: MOD, DIV, ROUND and RANDOM

Short code B6·8·19

DECLARE Cost : REAL
DECLARE Pence : INTEGER
Cost ← 7.456
OUTPUT ROUND(Cost, 2)
OUTPUT ROUND(Cost, 1)
OUTPUT ROUND(Cost, 0)
Pence ← 1234
OUTPUT DIV(Pence, 100), " pounds and ", MOD(Pence, 100), " pence"
ROUND, DIV and MOD at work on a cost and on a number of pence.

Output

7.46
7.5
7
12 pounds and 34 pence
Run and checked before printing
DECLARE Roll : INTEGER
DECLARE Count : INTEGER
DECLARE OutOfRange : INTEGER
OutOfRange ← 0
FOR Count ← 1 TO 1000
    Roll ← ROUND(RANDOM() * 5, 0) + 1
    IF Roll < 1 OR Roll > 6
      THEN
        OutOfRange ← OutOfRange + 1
    ENDIF
NEXT Count
OUTPUT "Rolls outside 1 to 6: ", OutOfRange
RANDOM() gives a different value on every run, so this program checks a thousand dice rolls instead of printing them.

Output

Rolls outside 1 to 6: 0
Run and checked before printing

Procedures and functions

Short code B6·8·20

PROCEDURE Banner(Title : STRING, Width : INTEGER)
    DECLARE Count : INTEGER
    DECLARE Edge : STRING
    Edge ← ""
    FOR Count ← 1 TO Width
        Edge ← Edge & "="
    NEXT Count
    OUTPUT Edge
    OUTPUT Title
    OUTPUT Edge
ENDPROCEDURE

CALL Banner("Sports Day", 10)
CALL Banner("Results", 7)
A procedure with two parameters, defined once and called twice with different values.

Output

==========
Sports Day
==========
=======
Results
=======
Run and checked before printing
FUNCTION Area(Length : REAL, Width : REAL) RETURNS REAL
    RETURN Length * Width
ENDFUNCTION

DECLARE Floor : REAL
Floor ← Area(4.5, 3.0) + Area(2.0, 2.5)
OUTPUT "Floor area: ", Floor, " square metres"
A function returns one value, so it is called inside an expression, never with CALL.

Output

Floor area: 18.5 square metres
Run and checked before printing
def Area(Length, Width):
    return Length * Width

Floor = Area(4.5, 3.0) + Area(2.0, 2.5)
print("Floor area:", Floor, "square metres")
The same function in Python, VB.NET and Java. Each language has its own way to say what a function returns.

Output

Floor area: 18.5 square metres
Run and checked before printing

Local and global variables

Short code B6·8·21

DECLARE Score : INTEGER

PROCEDURE AddBonus(Bonus : INTEGER)
    DECLARE Message : STRING
    Score ← Score + Bonus
    Message ← "Bonus added"
    OUTPUT Message
ENDPROCEDURE

Score ← 10
CALL AddBonus(5)
OUTPUT "Score: ", Score
Score is global: the main program and the procedure both use it. Message is local to the procedure.

Output

Bonus added
Score: 15
Run and checked before printing
DECLARE Score : INTEGER

PROCEDURE AddBonus(Bonus : INTEGER)
    DECLARE Message : STRING
    Score ← Score + Bonus
    Message ← "Bonus added"
    OUTPUT Message
ENDPROCEDURE

Score ← 10
CALL AddBonus(5)
OUTPUT "Score: ", Score
OUTPUT Message
The same program with one extra line at the end, trying to output the local variable from the main program. The interpreter refuses to run it.

Output

ERROR: Line 13: 'Message' has not been DECLAREd — add DECLARE Message : <TYPE> before using it
Run and checked before printing

Writing maintainable programs

Short code B6·8·22

DECLARE A : REAL
DECLARE B : REAL
INPUT B
A ← B * 1.2
OUTPUT A
Hard to maintain: it works, but what are A, B and 1.2?

Output

› 50
60
Run and checked before printing
// Adds sales tax to a cost typed in by the user
CONSTANT TaxRate ← 0.2

FUNCTION WithTax(Cost : REAL) RETURNS REAL
    RETURN Cost * (1 + TaxRate)
ENDFUNCTION

DECLARE ShopPrice : REAL
OUTPUT "Cost before tax?"
INPUT ShopPrice
OUTPUT "Cost with tax: ", WithTax(ShopPrice)
The same program written to be maintained: a constant, meaningful identifiers, a comment and a function. Same input, same answer.

Output

Cost before tax?
› 50
Cost with tax: 60
Run and checked before printing

One-dimensional arrays

Short code B6·8·23

DECLARE Temp : ARRAY[1:5] OF REAL
DECLARE Day : INTEGER
DECLARE Total : REAL
DECLARE Average : REAL
Total ← 0.0
FOR Day ← 1 TO 5
    INPUT Temp[Day]
    Total ← Total + Temp[Day]
NEXT Day
Average ← Total / 5
OUTPUT "Average: ", Average
FOR Day ← 1 TO 5
    IF Temp[Day] > Average
      THEN
        OUTPUT "Day ", Day, " was warmer: ", Temp[Day]
    ENDIF
NEXT Day
Five temperatures go into an array in one loop; a second loop reads them back. Without the array, the values would be gone before the average was known.

Output

› 21.5
› 19.0
› 24.5
› 22.5
› 18.0
Average: 21.1
Day 1 was warmer: 21.5
Day 3 was warmer: 24.5
Day 4 was warmer: 22.5
Run and checked before printing
Temp = [0.0, 0.0, 0.0, 0.0, 0.0]
Total = 0.0
for Day in range(5):
    Temp[Day] = float(input())
    Total = Total + Temp[Day]
Average = Total / 5
print("Average:", Average)
for Day in range(5):
    if Temp[Day] > Average:
        print("Day", Day + 1, "was warmer:", Temp[Day])
The same program in Python, VB.NET and Java. Their arrays (lists in Python) start at index 0, so day d is stored at d − 1.

Output

Average: 21.1
Day 1 was warmer: 21.5
Day 3 was warmer: 24.5
Day 4 was warmer: 22.5
Run and checked before printing

Two-dimensional arrays

Short code B6·8·24

DECLARE Player : INTEGER
DECLARE Game : INTEGER
DECLARE RowTotal : INTEGER
FOR Player ← 1 TO 3
    RowTotal ← 0
    FOR Game ← 1 TO 4
        RowTotal ← RowTotal + Points[Player, Game]
    NEXT Game
    OUTPUT "Player ", Player, ": ", RowTotal
NEXT Player
Row totals with nested loops. Points[1:3, 1:4] already holds the scores in the table above (3 players, 4 rounds).

Output

Player 1: 28
Player 2: 29
Player 3: 32
Run and checked before printing
DECLARE Player : INTEGER
DECLARE Game : INTEGER
DECLARE ColTotal : INTEGER
FOR Game ← 1 TO 4
    ColTotal ← 0
    FOR Player ← 1 TO 3
        ColTotal ← ColTotal + Points[Player, Game]
    NEXT Player
    OUTPUT "Round ", Game, ": ", ColTotal
NEXT Game
Column totals: swap the loops, so the outer loop walks along the rounds and the inner loop down the players.

Output

Round 1: 24
Round 2: 21
Round 3: 20
Round 4: 24
Run and checked before printing
Points = [[8, 5, 9, 6],
          [7, 10, 4, 8],
          [9, 6, 7, 10]]
for Player in range(3):
    RowTotal = 0
    for Round in range(4):
        RowTotal = RowTotal + Points[Player][Round]
    print("Player", Player + 1, ":", RowTotal)
Row totals in Python, VB.NET and Java. Python stores a 2D array as a list of lists, so Points[1][2] is row 1, column 2 counting from 0.

Output

Player 1 : 28
Player 2 : 29
Player 3 : 32
Run and checked before printing

File handling

Short code B6·8·25

DECLARE Name : STRING
DECLARE Score : INTEGER
OUTPUT "Name?"
INPUT Name
OUTPUT "Score?"
INPUT Score
OPENFILE "Best.txt" FOR WRITE
WRITEFILE "Best.txt", Name
WRITEFILE "Best.txt", Score
CLOSEFILE "Best.txt"
OUTPUT "Saved"
Writing: the player's name and score are saved in Best.txt, one item per line.

Output

Name?
› Amira
Score?
› 4820
Saved
Run and checked before printing
DECLARE Name : STRING
DECLARE ScoreText : STRING
OPENFILE "Best.txt" FOR READ
READFILE "Best.txt", Name
READFILE "Best.txt", ScoreText
CLOSEFILE "Best.txt"
OUTPUT "Best so far: ", Name, " with ", ScoreText
Reading, in a later run of a different program: the items come back in the order they were written. Both lines go into STRING variables, which can hold any line. (Best.txt holds the two lines written above.)

Output

Best so far: Amira with 4820
Run and checked before printing
CONSTANT Dishes ← 3
DECLARE Item : INTEGER
DECLARE Dish : STRING
OPENFILE "Menu.txt" FOR READ
FOR Item ← 1 TO Dishes
    READFILE "Menu.txt", Dish
    OUTPUT Item, ". ", Dish
NEXT Item
CLOSEFILE "Menu.txt"
Reading lines of text in a loop. This pseudocode has no test for the end of a file, so the program must know how many lines to read: here a constant.

Output

1. Vegetable soup
2. Chicken wrap
3. Fruit salad
Run and checked before printing

Putting it together: the 15-mark program

Short code B6·8·26

// Smoothie sales: 3 smoothies over 3 days
CONSTANT Days ← 3
DECLARE Smoothie : ARRAY[1:3] OF STRING
DECLARE Sales : ARRAY[1:3, 1:3] OF INTEGER
DECLARE Item : INTEGER
DECLARE Day : INTEGER
DECLARE ItemTotal : INTEGER
DECLARE GrandTotal : INTEGER
DECLARE BestTotal : INTEGER
DECLARE Best : INTEGER

// Inputs a whole number and returns it once it is from Low to High
FUNCTION GetValid(Low : INTEGER, High : INTEGER) RETURNS INTEGER
    DECLARE Amount : INTEGER
    INPUT Amount
    WHILE Amount < Low OR Amount > High DO
        OUTPUT Low, " to ", High, " only, try again"
        INPUT Amount
    ENDWHILE
    RETURN Amount
ENDFUNCTION

Smoothie[1] ← "Mango"
Smoothie[2] ← "Berry"
Smoothie[3] ← "Green"
// Input and store each day's sales of each smoothie
FOR Item ← 1 TO 3
    OUTPUT "Sales of ", Smoothie[Item], " for each day:"
    FOR Day ← 1 TO Days
        Sales[Item, Day] ← GetValid(0, 200)
    NEXT Day
NEXT Item
// Total each smoothie and find the best seller
GrandTotal ← 0
BestTotal ← -1
Best ← 1
FOR Item ← 1 TO 3
    ItemTotal ← 0
    FOR Day ← 1 TO Days
        ItemTotal ← ItemTotal + Sales[Item, Day]
    NEXT Day
    OUTPUT Smoothie[Item], ": ", ItemTotal
    IF ItemTotal > BestTotal
      THEN
        BestTotal ← ItemTotal
        Best ← Item
    ENDIF
    GrandTotal ← GrandTotal + ItemTotal
NEXT Item
OUTPUT "Best seller: ", Smoothie[Best]
OUTPUT "Average sold per day: ", ROUND(GrandTotal / Days, 1)
The smoothie program, run with nine sales figures and two mistakes (250 and −5).

Output

Sales of Mango for each day:
› 45
› 52
› 38
Sales of Berry for each day:
› 60
› 250
0 to 200 only, try again
› 61
› 58
Sales of Green for each day:
› 30
› -5
0 to 200 only, try again
› 33
› 29
Mango: 135
Berry: 179
Green: 92
Best seller: Berry
Average sold per day: 135.3
Run and checked before printing
# Smoothie sales: 3 smoothies over 3 days
DAYS = 3

# Inputs a whole number; returns it once it is Low to High
def GetValid(Low, High):
    Amount = int(input())
    while Amount < Low or Amount > High:
        print(Low, "to", High, "only, try again")
        Amount = int(input())
    return Amount

Smoothie = ["Mango", "Berry", "Green"]
Sales = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
# Input and store each day's sales of each smoothie
for Item in range(3):
    print("Sales of", Smoothie[Item], "for each day:")
    for Day in range(DAYS):
        Sales[Item][Day] = GetValid(0, 200)
# Total each smoothie and find the best seller
GrandTotal = 0
BestTotal = -1
Best = 0
for Item in range(3):
    ItemTotal = 0
    for Day in range(DAYS):
        ItemTotal = ItemTotal + Sales[Item][Day]
    print(Smoothie[Item] + ":", ItemTotal)
    if ItemTotal > BestTotal:
        BestTotal = ItemTotal
        Best = Item
    GrandTotal = GrandTotal + ItemTotal
print("Best seller:", Smoothie[Best])
print("Average sold per day:",
      round(GrandTotal / DAYS, 1))
The smoothie program in Python, VB.NET and Java, given the same eleven values.

Output

Sales of Mango for each day:
Sales of Berry for each day:
0 to 200 only, try again
Sales of Green for each day:
0 to 200 only, try again
Mango: 135
Berry: 179
Green: 92
Best seller: Berry
Average sold per day: 135.3
Run and checked before printing

Command-word coach

Short code B6·8·27

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

Workbook: Programming

Short code W6·8 · Algorithms, Programming and Logic 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.

Starter files

Short code W6·8·K

Data files and skeleton code in Pseudocode, Python, VB.NET, Java for this chapter's tasks arrive here with the chapter.

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