Paper 2: Pseudocode step by step (arrays, functions, procedures)

Paper 2: Pseudocode step by step (arrays, functions, procedures)

Functions and procedures: parameters, BYREF and module tables

Functions and procedures AS Level 15 min read

On this page
  1. What you need to be able to do
  2. Why modules matter so much
  3. Procedure or function?
  4. Local and global variables
  5. By value and by reference
  6. Reading a Module | Description table
  7. Worked example: a module that uses another module
  8. Practice: three levels
  9. Mistakes that lose marks
  10. Can I do this?

What you need to be able to do

Syllabus 11.3 Structured programming (Paper 2)
  • 11.3Write a PROCEDURE and a FUNCTION with parameters, and say when to use each.
  • 11.3Call them correctly: CALL a procedure; use a function's return value in an expression.
  • 11.3Explain and use BY VALUE and BY REFERENCE parameters, and local and global variables.
  • 9.2Turn a Module | Description table into the header and the body of a module.

You need: Strings (most modules in the exam work on strings).

Why modules matter so much

The long questions at the end of Paper 2 always describe a program as a set of modules (procedures and functions) in a table, then ask you to write one or two of them. In 31 of the 33 papers we checked, that table was there. If you can turn a description into a correct header, half the marks are already on the way.

Procedure or function?

PROCEDUREFUNCTION
What it doescarries out a taskworks something out and returns one value
HeaderPROCEDURE ShowLine(N : INTEGER)FUNCTION Square(N : INTEGER) RETURNS INTEGER
Ends withENDPROCEDUREENDFUNCTION
Insideno RETURN valuemust reach RETURN value (of the RETURNS type)
How you use ita statement on its own: CALL ShowLine(5)inside an expression: Area ← Square(Side) or OUTPUT Square(4)
The description says“outputs …”, “stores …”, “writes to the file …”“returns …”
One of each, and how they are used
PROCEDURE ShowLine(N : INTEGER, Symbol : CHAR)   DECLARE i : INTEGER   DECLARE Line : STRING   Line ← ""   FOR i ← 1 TO N      Line ← Line & Symbol   NEXT i   OUTPUT LineENDPROCEDURE FUNCTION Square(N : INTEGER) RETURNS INTEGER   RETURN N * NENDFUNCTION CALL ShowLine(5, '*')          // outputs *****OUTPUT Square(7)               // outputs 49
Parameter: the name in the header that receives a value (N, Symbol). Argument: the actual value passed in the call (5, '*'). They are matched by order, not by name.
A FUNCTION's value must be used: CALL Square(7) throws the answer away, and Square(7) on its own line is not a statement. A PROCEDURE has no value: X ← ShowLine(5, '*') is wrong.

Local and global variables

Local

Declared inside a module. Exists only while the module runs, and only that module can use it. Parameters are local too. Use local variables for everything that is only needed inside.

Global

Declared in the main program, outside every module. Every module can read and change it. In the exam, arrays are usually global (“a global 1D array Stock …”).
The exam says “a global array Data”. Do you pass Data into your module as a parameter? No: global means the module can use Data directly. Only pass what the description lists as parameters.

By value and by reference

A parameter can receive its value in two ways:

BYVAL (by value) - the defaultBYREF (by reference)
What is passeda copy of the valuethe address of the variable: the module works on the original
Change it inside the moduleonly the copy changes; the caller's variable is not changedthe caller's variable is changed
Use it whenthe module only needs to read the value (almost always)the module must give back more than one value, or change the caller's variable
Swap needs BYREF
PROCEDURE Swap(BYREF A : INTEGER, BYREF B : INTEGER)   DECLARE Temp : INTEGER   Temp ← A   A ← B   B ← TempENDPROCEDURE
12
X, Y38
Before CALL Swap(X, Y): X = 3, Y = 8.
12
X, Y83
After, with BYREF: X = 8, Y = 3. With BYVAL the module swaps two copies and X, Y stay 3 and 8 - we ran both versions to check.
Only a variable (or an array element) can be passed BYREF: CALL Swap(X, 5) makes no sense, because 5 has no box to change.

Reading a Module | Description table

This is how the exam describes a module. Read it one bullet at a time - every bullet becomes part of your code, and the mark scheme gives marks bullet by bullet.

ModuleDescription
CountChar()
  • called with two parameters: a string and a character
  • counts how many times the character appears in the string (capital and small letters count as the same)
  • returns the count
BulletWhat you write
“called with two parameters: a string and a character”the header's parameter list: (ThisString : STRING, ThisChar : CHAR)
“returns the count”it is a FUNCTION … RETURNS INTEGER and a RETURN Count at the end
“counts how many times …”the body: a counter set to 0, a loop over the string (strings pattern 1), an IF
“capital and small letters count as the same”compare LCASE(Ch) = LCASE(ThisChar)
The finished module
FUNCTION CountChar(ThisString : STRING, ThisChar : CHAR) RETURNS INTEGER   DECLARE Count, i : INTEGER   Count ← 0   FOR i ← 1 TO LENGTH(ThisString)      IF LCASE(MID(ThisString, i, 1)) = LCASE(ThisChar) THEN         Count ← Count + 1      ENDIF   NEXT i   RETURN CountENDFUNCTION
A checklist for every module you write: header matches the description (name, parameters with types, RETURNS type) · local variables declared · counters/totals initialised · loop over the right range · RETURN (function) or OUTPUT/store (procedure) · the right END word.

Worked example: a module that uses another module

ModuleDescription
IsVowel()
  • called with a parameter of type CHAR
  • returns TRUE if the character is a vowel (a, e, i, o, u; small or capital), otherwise FALSE
Abbreviate()
  • called with a parameter of type STRING
  • returns the string with every vowel removed, except that the first character is always kept
  • must use IsVowel()
Example 1 · IsVowel() and Abbreviate() (own example) ★★ Medium
Q1Practice7 marks

Write pseudocode for the two modules in the table above. For example, Abbreviate("Islamabad") returns "Islmbd".

1 Read it with me what is actually happening?

Two small jobs. The first checks one character. The second goes along a word and keeps only the characters the first one says are not vowels.

  • returns TRUE … otherwise FALSEa FUNCTION … RETURNS BOOLEAN
  • returns the stringa FUNCTION … RETURNS STRING
  • must use IsVowel()a mark is given for calling it: don't test for vowels again inside Abbreviate
2 What is it asking for? the target, part by part
  • 1IsVowel(Ch) → BOOLEANone IF
  • 2Abbreviate(Word) → STRINGstrings pattern 2 (build a new string)
3 What do we know? everything the question gives us
  • a e i o uthe vowels
  • first characteralways kept
  • “small or capital” means LCASE (or UCASE) before comparing.
4 Plan the route work backwards from what we want
FindKey ideaAlready have itWork out firstTrap
  • FindAbbreviate(Word)
    • Already have itIsVowel(Ch) does the test
    • Work out firstResult starts as LEFT(Word, 1)
    • Key idealoop from 2: add MID(Word, i, 1) when IsVowel(…) = FALSE
      • TrapIsVowel returns a value: use it in the IF, never CALL it
Why does the loop start at 2?

Position 1 is already in Result and must be kept even if it is a vowel ("Oven" → "Ovn").

Could IsVowel be a procedure?

No: it has to give back TRUE/FALSE, so it is a function.

5 Now solve it have a go on paper first, then open the worked solution
  1. Write IsVowel: make the character small with LCASE, compare it with the five vowels, RETURN TRUE or FALSE.
  2. Write Abbreviate: Result ← first character; loop from 2 to LENGTH; add each character for which IsVowel is FALSE; RETURN Result.
Model answer
FUNCTION IsVowel(Ch : CHAR) RETURNS BOOLEAN   DECLARE L : CHAR   L ← LCASE(Ch)   IF L = 'a' OR L = 'e' OR L = 'i' OR L = 'o' OR L = 'u' THEN      RETURN TRUE   ELSE      RETURN FALSE   ENDIFENDFUNCTION FUNCTION Abbreviate(Word : STRING) RETURNS STRING   DECLARE Result : STRING   DECLARE i : INTEGER   Result ← LEFT(Word, 1)   FOR i ← 2 TO LENGTH(Word)      IF IsVowel(MID(Word, i, 1)) = FALSE THEN         Result ← Result & MID(Word, i, 1)      ENDIF   NEXT i   RETURN ResultENDFUNCTION
6 Check it does the answer make sense?

Tested: Abbreviate("Islamabad") = "Islmbd", Abbreviate("Oven") = "Ovn", IsVowel('E') = TRUE.

Practice: three levels

L1 Basic

One small module.

L1.1 Cube

Write a function Cube() that takes an integer and returns its cube.

Show the model answer
FUNCTION Cube(N : INTEGER) RETURNS INTEGER   RETURN N * N * NENDFUNCTION

L1.2 Greeting

Write a procedure Greet() that takes a name and outputs Hello, followed by the name. Then write the line that calls it for the name "Ayesha".

Show the model answer
PROCEDURE Greet(Name : STRING)   OUTPUT "Hello, ", NameENDPROCEDURE CALL Greet("Ayesha")

A procedure is used with CALL.

L1.3 IsEven

Write a function IsEven() that takes an integer and returns TRUE if it is even, otherwise FALSE.

Show the model answer
FUNCTION IsEven(N : INTEGER) RETURNS BOOLEAN   IF N MOD 2 = 0 THEN      RETURN TRUE   ELSE      RETURN FALSE   ENDIFENDFUNCTION

Shorter, also correct: RETURN N MOD 2 = 0.

L2 Medium

Choose the module type and the parameters.

L2.1 Largest of three

Write a function Max3() that takes three integers and returns the largest.

Show the model answer
FUNCTION Max3(A : INTEGER, B : INTEGER, C : INTEGER) RETURNS INTEGER   DECLARE Big : INTEGER   Big ← A   IF B > Big THEN      Big ← B   ENDIF   IF C > Big THEN      Big ← C   ENDIF   RETURN BigENDFUNCTION

Start with the first one and replace it whenever a bigger value turns up - the same idea as the maximum of an array.

L2.2 Divide with a remainder

Write a procedure Divide() that takes two integers and gives back the quotient and the remainder to the calling program, using two more parameters.

Show the model answer
PROCEDURE Divide(A : INTEGER, B : INTEGER, BYREF Q : INTEGER, BYREF R : INTEGER)   Q ← A DIV B   R ← A MOD BENDPROCEDURE

Two values come back, so a function (one value) is not enough: the two extra parameters are BYREF.

L2.3 Valid product code

Write a function ValidCode() that takes a string and returns TRUE if it is a valid product code: exactly 6 characters, the first two are capital letters, and the last four are digits (e.g. "LH2041").

Show the model answer
FUNCTION ValidCode(Code : STRING) RETURNS BOOLEAN   DECLARE i : INTEGER   DECLARE Ch : CHAR   IF LENGTH(Code) <> 6 THEN      RETURN FALSE   ENDIF   FOR i ← 1 TO 6      Ch ← MID(Code, i, 1)      IF i <= 2 THEN         IF Ch < 'A' OR Ch > 'Z' THEN            RETURN FALSE         ENDIF      ELSE         IF Ch < '0' OR Ch > '9' THEN            RETURN FALSE         ENDIF      ENDIF   NEXT i   RETURN TRUEENDFUNCTION

Return FALSE as soon as one rule is broken; reaching the end means every rule passed. (A flag set to FALSE and one RETURN at the end is also fine.)

L3 Hard

From a Module | Description table, like the exam.

L3.1 From a description

Write pseudocode for this module.

ModuleDescription
GetMark()
  • called with no parameters
  • prompts for and inputs a mark until it is an integer from 0 to 100 (inputs are typed as strings)
  • returns the valid mark as an integer
Hint

Which two checks are needed, and in which order?

Show the model answer
FUNCTION GetMark() RETURNS INTEGER   DECLARE Entry : STRING   DECLARE Mark : INTEGER   DECLARE Valid : BOOLEAN   REPEAT      OUTPUT "Enter a mark from 0 to 100"      INPUT Entry      Valid ← FALSE      IF IS_NUM(Entry) = TRUE THEN         Mark ← STR_TO_NUM(Entry)         IF Mark >= 0 AND Mark <= 100 THEN            Valid ← TRUE         ENDIF      ENDIF   UNTIL Valid = TRUE   RETURN MarkENDFUNCTION

Check IS_NUM before STR_TO_NUM: converting "abc" would fail. REPEAT because there is always at least one input.

L3.2 Two modules

Write pseudocode for both modules.

ModuleDescription
Initials()
  • called with a full name (names separated by single spaces)
  • returns the initials in capitals, e.g. "Ali raza Khan" → "ARK"
Username()
  • called with a full name and a year of birth (INTEGER)
  • returns the initials followed by the last two digits of the year, e.g. ("Ali raza Khan", 2009) → "ARK09"
  • must use Initials()
Hint

What does 2009 MOD 100 give? Why is that a problem?

Show the model answer
FUNCTION Initials(FullName : STRING) RETURNS STRING   DECLARE Result : STRING   DECLARE i : INTEGER   Result ← LEFT(FullName, 1)   FOR i ← 2 TO LENGTH(FullName)      IF MID(FullName, i - 1, 1) = ' ' THEN         Result ← Result & MID(FullName, i, 1)      ENDIF   NEXT i   RETURN TO_UPPER(Result)ENDFUNCTION FUNCTION Username(FullName : STRING, Year : INTEGER) RETURNS STRING   DECLARE YearText : STRING   YearText ← NUM_TO_STR(Year)   RETURN Initials(FullName) & RIGHT(YearText, 2)ENDFUNCTION

The last two digits: turn the year into a string and take RIGHT(…, 2). (Year MOD 100 gives 9 for 2009, losing the 0.)

L3.3 Find the smallest and largest

Write a procedure MinMax() that inputs 5 integers and gives both the smallest and the largest back to the calling program. Then write the main-program lines that call it and output both values.

Show the model answer
PROCEDURE MinMax(BYREF Small : INTEGER, BYREF Big : INTEGER)   DECLARE N, i : INTEGER   INPUT N   Small ← N   Big ← N   FOR i ← 2 TO 5      INPUT N      IF N < Small THEN         Small ← N      ENDIF      IF N > Big THEN         Big ← N      ENDIF   NEXT iENDPROCEDURE DECLARE Lowest, Highest : INTEGERCALL MinMax(Lowest, Highest)OUTPUT Lowest, " ", Highest

Two answers to give back → a procedure with two BYREF parameters. The main program declares the variables and passes them in.

Mistakes that lose marks

MistakeWrite this instead
No types in the header: FUNCTION Square(N)FUNCTION Square(N : INTEGER) RETURNS INTEGER
A function with no RETURN, or RETURN in a procedureFunction: every route reaches RETURN. Procedure: no RETURN value.
Using CALL with a functionUse the value: Result ← Square(X)
INPUT inside a module that is “called with” the valueThe value arrives as a parameter: don't INPUT it again
OUTPUT inside a module that “returns” the valueRETURN it; the caller decides what to do with it
Passing a global array as a parameter when the question says it is globalJust use it by name

Can I do this?

Anything unticked: revise that section first. All ticked: take the quiz.

The multiple-choice and guided questions need JavaScript. The concept checks and exam practice below work without it.

Concept checks

Answer each one in your head first, then open it.

1Why does the exam ask you to “use” an existing module rather than write the code again?Show answer

To show you can reuse a module through its interface; the mark is for calling it with the right arguments and using its result.

2What is the difference between a parameter and an argument?Show answer

The parameter is the name in the module's header; the argument is the value given in the call.

3Why is RETURN Count placed after the loop, not inside it?Show answer

Inside, the function would end on the first pass and return a count of at most 1.

Your progress on this note is saved when JavaScript is on.

⬇️ Download this chapter as a PDF: Full notes · Worksheets · Answers