Book 6 · Chapter 8
Programming
B6·8This 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.
For the whole chapter
- Topic pageProgramming
B6·8·T - QuizProgramming
B6·8·Q1 - LabProgramming tasks (auto-marked)
B6·8·X1 - LabO Level Python, step by step
B6·8·X2 - LabPseudocode Playground
B6·8·X3 - LabFlowchart from pseudocode
B6·8·X4 - LabTranslate to Python / VB / Java
B6·8·X5
§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
- FlashcardsFlashcards §8.1: Variables, data types & constructs
B6·8·F1 - FlashcardsFlashcards §8.1: Operators, strings & library routines
B6·8·F2 - FlashcardsFlashcards §8.1: Procedures, functions, scope & maintainability
B6·8·F3 - Past-paper questionsPast-paper questions §8.1 (programming-concepts)
- Past-paper questionsPast-paper questions §8.1 (totalling-counting-and-string-handling-length-substring-uppe)
- Past-paper questionsPast-paper questions §8.1 (procedures-functions-and-parameters-local-and-global-variabl)
§8.2 Arrays
Short code B6·8·2
- FlashcardsFlashcards §8.2–8.3: Arrays & file handling
B6·8·F4 - Past-paper questionsPast-paper questions §8.2 (arrays)
B6·8·2
§8.3 File handling
Short code B6·8·3
- FlashcardsFlashcards §8.2–8.3: Arrays & file handling
B6·8·F4 - Past-paper questionsPast-paper questions §8.3 (file-handling)
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? ", GameOverOutput
Zara has 3 lives Speed: 2.5 Grade: B Game over? FALSE
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: ", CostOutput
How many children? › 3 Total for one adult and 3 children: 23.5
DECLARE Left : INTEGER
DECLARE Right : INTEGER
Left ← 4
Right ← 9
Left ← Right
Right ← Left
OUTPUT Left, " ", RightSelection 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, " ", RightOutput
9 4
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
ENDIFOutput
Enter the mark (0 to 100) › 64 Pass
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
ENDIFOutput
Cup size? S, M or L › M Cost: 1.8
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)Output
Cup size? S, M or L Cost: 1.8
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!"Output
10 8 6 4 2 0 Lift off!
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"Output
Doubled after 8 years
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"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
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 / DaysOutput
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
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 IsTeenOutput
2 h 15 min 3.5 3 1 32 11 14 Teenager? TRUE Not a teenager? FALSE
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)Output
16 COMPUTER SCIENCE computer science Science ComSci
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: ", CountOutput
Letter a: 2
Word = "Avocado"
Count = 0
for Position in range(len(Word)):
Letter = Word[Position].lower()
if Letter == "a":
Count = Count + 1
print("Letter a:", Count)Output
Letter a: 2
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 RowOutput
.#. ###
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)% is the remainder operator in all three, the same job as MOD.Output
.#. ###
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"Output
7.46 7.5 7 12 pounds and 34 pence
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: ", OutOfRangeOutput
Rolls outside 1 to 6: 0
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)Output
========== Sports Day ========== ======= Results =======
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"Output
Floor area: 18.5 square metres
def Area(Length, Width):
return Length * Width
Floor = Area(4.5, 3.0) + Area(2.0, 2.5)
print("Floor area:", Floor, "square metres")Output
Floor area: 18.5 square metres
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: ", ScoreOutput
Bonus added Score: 15
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 MessageOutput
ERROR: Line 13: 'Message' has not been DECLAREd — add DECLARE Message : <TYPE> before using it
Writing maintainable programs
Short code B6·8·22
DECLARE A : REAL
DECLARE B : REAL
INPUT B
A ← B * 1.2
OUTPUT AOutput
› 50 60
// 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)Output
Cost before tax? › 50 Cost with tax: 60
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 DayOutput
› 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
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])Output
Average: 21.1 Day 1 was warmer: 21.5 Day 3 was warmer: 24.5 Day 4 was warmer: 22.5
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 PlayerOutput
Player 1: 28 Player 2: 29 Player 3: 32
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 GameOutput
Round 1: 24 Round 2: 21 Round 3: 20 Round 4: 24
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)Output
Player 1 : 28 Player 2 : 29 Player 3 : 32
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"Output
Name? › Amira Score? › 4820 Saved
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 ", ScoreTextOutput
Best so far: Amira with 4820
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"Output
1. Vegetable soup 2. Chicken wrap 3. Fruit salad
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)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
# 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))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
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.


