Skip to content
Cambridge AS & A Level9618

Structured Programming

Computer Science 9618 Chapter Notes

Last updated November 2026

ShareWhatsAppPost

Structured Programming notes as a printable PDF.

Read online free. Download a watermarked copy with a free account.

Read the notes

The full Structured Programming notes as text: skim, search, and jump between subtopics.

~19 min read

1. Procedures

A procedure is a module written once, between `PROCEDURE` and `ENDPROCEDURE`, and run when it is called. The procedure heading and ending are the first marks in a mark scheme.

A procedure carries out a task. In the papers it prompts and inputs values, tests them and outputs a message (`IsRA()`), outputs a result (`Calculate()`), or outputs a new string (`GetInitials()`). A function returns a (single) value and a procedure does not. A procedure is called by a statement of its own: `CALL IsRA()`.

Use a procedure where the same steps are needed in several places. Write them once as a module and replace each copy with a call. The module is designed and tested once, and any change needs to be made once only. The declaration of all variables used goes after the heading, so that they are local to the procedure.

Examiner insight

“In some solutions the variable declarations were placed before the procedure header. These were not then treated as local variables.” “A procedure header was usually included, but often the parameter or the corresponding ENDPROCEDURE statement was missing (MP1).”

Worked example 15 marks

A triangle has sides of length A, B and C. In this example, A is the length of the longest side.

This triangle is said to be right-angled if the following equation is true:

`A × A = (B × B) + (C × C)`

A procedure will be written to check whether three lengths represent a right-angled triangle. The lengths will be input in any sequence.

The procedure IsRA() will:

• prompt and input three integer values representing the three lengths

• test whether the three lengths correspond to the sides of a right-angled triangle

• output a suitable message.

The length of the longest side may not be the first value input.

Write pseudocode for the procedure IsRA().

  1. 1

    Procedure heading and ending, and declaration of all variables used: `PROCEDURE IsRA()`, `DECLARE a, b, c : INTEGER`, `ENDPROCEDURE` [1]

  2. 2

    Appropriate prompt and input for each length: `OUTPUT "Input length of the first side"`, `INPUT a`, and the same for `b` and `c` [1]

  3. 3

    One correct length test: `a * a = (b *b) + (c * c)` [1]

  4. 4

    All three length tests, joined by `OR`, because any of the three could be the longest side [1]

  5. 5

    Output one of two messages, following a reasonable attempt at a length test: `"It is right-angled"` or `"Not right-angled"` [1]

2. Parameters and the interface

A parameter is a value that a procedure or function receives. It is named in the header with its data type: `PROCEDURE Calculate(Expression : STRING)`. A procedure or function may have none, one or more parameters. The value written in the call is the argument: `CALL Calculate("34/7")`. Inside the module, use the parameter by name. Do not replace it with a prompt and an `INPUT`.

The header is the first line: the keyword, the identifier, the parameters and, for a function, `RETURNS` and a type. The interface is what a module takes in and gives back. For a function that checks a number against a required total, it is two integer parameters and a Boolean return value: `CheckNum(Number, Total : INTEGER) RETURNS BOOLEAN`.

A parameter can be passed by value or by reference. By reference, any change made to the parameter inside the module is reflected in the value in the calling module. By value, the change is not reflected: the arguments used are unchanged. By reference is written with BYREF in the header: `PROCEDURE Swap(BYREF Num1, Num2 : INTEGER)`.

Examiner insight

“A significant number of solutions attempted to INPUT the three parts of the expression.” “Candidates needed to recognise that as this was a three-mark question, so simply referring to ‘ByRef’ without explanation would not gain full marks.”

Worked example 17 marks

A simple arithmetic expression is stored as a string in the format:

``` <Value1><Operator><Value2> ```

An operator character is one of the following: '+' '-' '*' '/'

Example arithmetic expression strings: "803+1904" and "34/7"

A procedure Calculate() will:

• take an arithmetic expression string as a parameter

• evaluate the expression

• output the result.

Assume:

• the string contains only numeric digits and a single operator character

• Value1 and Value2 represent integer values

• Value1 and Value2 are unsigned (they will not be preceded by '+' or '-').

Write pseudocode for the procedure Calculate().

  1. 1

    Declaration of local variables for the three parts: `DECLARE Par1, Par2, Par3 : STRING` [1]

  2. 2

    Loop to the end of the parameter string, or until the operator is found: `FOR Index ← 1 TO LENGTH(Expression)` [1]

  3. 3

    Extract a character in the loop: `ThisChar ← MID(Expression, Index, 1)` [1]

  4. 4

    Attempt at extraction of the three parts of the expression with substring functions [1]

  5. 5

    Completely correct extraction of all three parts: `LEFT(Expression, Index - 1)`, the operator, `RIGHT(Expression, LENGTH(Expression) - Index)` [1]

  6. 6

    Convert each string to a number: `STR_TO_NUM(Par1)` and `STR_TO_NUM(Par3)` [1]

  7. 7

    Interpret the operators (`CASE OF Par2`), do the matching calculation for all four, and output the result (two mark points; the maximum is 7) [1]

  8. 8

    ``` PROCEDURE Calculate(Expression : STRING) DECLARE Val1, Val2, Index : INTEGER DECLARE Result : REAL DECLARE Par1, Par2, Par3, ThisChar : STRING FOR Index ← 1 TO LENGTH(Expression) ThisChar ← MID(Expression, Index, 1) IF IS_NUM(ThisChar) = FALSE THEN Par1 ← LEFT(Expression, Index - 1) Par2 ← ThisChar Par3 ← RIGHT(Expression, LENGTH(Expression) - Index) ENDIF NEXT Index Val1 ← STR_TO_NUM(Par1) Val2 ← STR_TO_NUM(Par3) CASE OF Par2 '+' : Result ← Val1 + Val2 '-' : Result ← Val1 - Val2 '*' : Result ← Val1 * Val2 '/' : Result ← Val1 / Val2 ENDCASE OUTPUT Result ENDPROCEDURE ```

3. Defining a function

A function is a named module that returns a (single) value. A procedure does not. The heading is `FUNCTION`, the ending is `ENDFUNCTION`, and the header gives the return type after `RETURNS`: `FUNCTION MakeString(Count : INTEGER, AChar : CHAR) RETURNS STRING`.

The value is sent back with `RETURN`, and `RETURN` ends the function. `OUTPUT` only displays a value. It does not give it to the code that made the call. Every route through the function must reach a `RETURN`, so the value is returned correctly in both cases of an `IF`.

Variables the function needs are declared inside it. A parameter name is an identifier, so it cannot be a data type name such as `CHAR`.

Examiner insight

“A very common error here was to use the identifier name Char for one of the parameters. Char is one of the pseudocode data types and therefore cannot be used in the pseudocode as an identifier.” “In many cases a value was returned either if the word was found, or if it was not found, but not in both cases.”

Worked example 16 marks

A function MakeString() will:

  1. take two parameters:

• a count as an integer

• a character

  1. generate a string of length equal to the count, made up of the character
  1. return the string generated, or return "ERROR" if the count is less than 1.

For example, the function call `MakeString(3, 'Z')` will return the string "ZZZ".

Write pseudocode for function MakeString().

  1. 1

    Function heading and end, including parameters and return type: `FUNCTION MakeString(Count : INTEGER, AChar : CHAR) RETURNS STRING` [1]

  2. 2

    Declaration of the locals `Index` and `MyString` [1]

  3. 3

    Test for `Count < 1` and, if true, assign `"ERROR"` to `MyString` (or an immediate `RETURN`) [1]

  4. 4

    Loop for `Count` iterations: `FOR Index ← 1 TO Count` [1]

  5. 5

    Concatenate in the loop, with `MyString` set to `""` first: `MyString ← MyString & AChar` [1]

  6. 6

    Return the STRING correctly in both cases: `RETURN MyString` [1]

4. Using a function in an expression

Use a function where a module's job is to produce one value that the calling code then uses. In the papers such modules say "Returns": `GetStart()`, `GetWord()` and `IgnoreWord()`.

A function is used in an expression: the return value replaces the call. Write `IF Valid(MyString) = TRUE THEN`. The call has the arguments only, with no types and no `RETURNS`. `CALL Valid(MyString)` then `IF RESULT = TRUE THEN` is invalid. Store the result of GetStart() in a variable, or test the result of IgnoreWord() directly.

If `Calculate()` is changed to a function that returns the value, its header has one parameter and a REAL return value: `FUNCTION Calculate(Expression : STRING) RETURNS REAL`.

Examiner insight

“The use of the user-defined functions proved too challenging for many.” “Although the module description points to a solution using the three user-defined functions GetStart(), GetWord() and IgnoreWord(), many candidates attempted to implement this module using only the functions given in the insert. This was generally not successful.”

Worked example 18 marks

A program is needed to take a string containing a full name and to produce a new string of initials.

Some words in the full name will be ignored. For example, "the", "and", "of", "for" and "to" may all be ignored.

Each letter of the new string must be upper case. For example, "Integrated Development Environment" gives "IDE" and "The American Standard Code for Information Interchange" gives "ASCII".

The programmer has decided to use the following global variables:

• a ten element 1D array IgnoreList of type STRING to store the ignored words

• a string FNString to store the full name string.

Assume that:

• each alphabetic character in the full name string may be either upper or lower case

• the full name string contains at least one word.

The programmer has started to define program modules as follows:

Write pseudocode for the module GetInitials().

ModuleDescription
GetStart()Called with an INTEGER as its parameter, representing the number of a word in FNString. Returns the character start position of that word in FNString or returns -1 if that word does not exist. For example: GetStart(3) applied to "hot and cold" returns 9
GetWord()Called with the position of the first character of a word in FNString as its parameter. Returns the word from FNString. For example: if FNString contains the string "hot and cold", GetWord(9) returns "cold"
IgnoreWord()Called with a STRING parameter representing a word. Searches for the word in the IgnoreList array. Returns TRUE if the word is found, otherwise returns FALSE
GetInitials()Processes the sequence of words in the full name one word at a time. Calls GetStart(), GetWord() and IgnoreWord() to process each word to form the new string. Outputs the new string
  1. 1

    Declare `NewString` and initialise it to the empty string: `NewString ← ""` [1]

  2. 2

    Conditional loop to pick out all the words from FNString: `REPEAT ... UNTIL Index = -1` [1]

  3. 3

    Evaluate the result of `GetStart()` in the loop: `Index ← GetStart(ThisWordNum)` [1]

  4. 4

    Test the result, `IF Index <> -1 THEN`, and if it is true: [1]

  5. 5

    Assign the result of `GetWord()` to a variable in the loop: `NextWord ← GetWord(Index)` [1]

  6. 6

    Test the result of `IgnoreWord()` in the loop: `IF IgnoreWord(NextWord) = FALSE THEN` [1]

  7. 7

    If the word is not ignored, add its initial to `NewString`: `NewString ← NewString & UCASE(LEFT(NextWord, 1))` [1]

  8. 8

    Increment `ThisWordNum`, which must have been initialised before the loop [1]

  9. 9

    Output `NewString` in upper case, outside the loop (a ninth point; the maximum is 8)

  10. 10

    ``` PROCEDURE GetInitials() DECLARE NewString, NextWord : STRING DECLARE ThisWordNum, Index : INTEGER ThisWordNum ← 0 NewString ← "" REPEAT ThisWordNum ← ThisWordNum + 1 Index ← GetStart(ThisWordNum) IF Index <> -1 THEN NextWord ← GetWord(Index) IF IgnoreWord(NextWord) = FALSE THEN NewString ← NewString & UCASE(LEFT(NextWord, 1)) ENDIF ENDIF UNTIL Index = -1 OUTPUT NewString ENDPROCEDURE ```

5. Writing efficient pseudocode

Efficient pseudocode does the job with no unnecessary work. Use the functions in the insert instead of a loop where one statement does the job. A string padded with spaces to 25 characters can be formed with `LEFT(Plaintext & Fill, 25)`, where `Fill` is a constant of 24 spaces, and no loop. The loop solution also earns the marks, but the non loop solution is shorter.

Stop as soon as the answer is known. An immediate RETURN inside the loop is enough, provided the value for "not found" is returned after the loop. Do not add steps the question does not ask for, such as converting case.

Keep each statement valid. Do not use a standard function name or a data type as a variable name (`Length`, `Char`). Write a full comparison for each condition: `IF x = 3 OR x = 4 OR x = 5 THEN`, not `IF x = 3 OR 4 OR 5 THEN`.

Examiner insight

“A small number of candidates lost a mark for wrongly converting both characters being compared to the same case. The question made no mention of case conversion either explicitly or implicitly.” “Solutions that had implemented an immediate RETURN within the loop simply had to then return –1 after the loop to gain the mark.”

Worked example 16 marks

A program is being developed to process bank card information. When a card number is displayed, all the characters except the last four are replaced with the asterisk character '*'.

Card numbers are stored as strings. The strings are between 10 and 20 characters in length. For example, "1234567890" becomes six asterisks followed by "7890".

The function Conceal() will:

• take a numeric string as a parameter representing the card number

• return a string in which the asterisk character replaces all except the last four characters of the card number parameter.

Write pseudocode for the function Conceal().

  1. 1

    Function heading, parameter, return type and ending: `FUNCTION Conceal(CardNumber : STRING) RETURNS STRING` [1]

  2. 2

    Declaration of all local variables used: `MaskedString` and `Count` [1]

  3. 3

    Calculate the number of asterisks required: `Count ← LENGTH(CardNumber) - 4` [1]

  4. 4

    Trim the asterisk string to that number: `LEFT(Asterisks, Count)`, with `Asterisks` a constant of 20 asterisks [1]

  5. 5

    Extract the last four characters and concatenate them: `& RIGHT(CardNumber, 4)` (two mark points; the maximum is 6) [1]

  6. 6

    Return the masked string: `RETURN MaskedString` [1]

  7. 7

    ``` FUNCTION Conceal(CardNumber : STRING) RETURNS STRING DECLARE MaskedString : STRING DECLARE Count : INTEGER CONSTANT Asterisks = "" Count ← LENGTH(CardNumber) - 4 MaskedString ← LEFT(Asterisks, Count) & RIGHT(CardNumber, 4) RETURN MaskedString ENDFUNCTION ```

Recap

  • A procedure is called with CALL and carries out a task. A function returns a (single) value and a procedure does not; a function is used in an expression.
  • Heading and ending: PROCEDURE and ENDPROCEDURE, FUNCTION and ENDFUNCTION. A function's header ends with RETURNS and a type.
  • A parameter is named in the header with its type. An argument is the value in the call. The interface is the parameters a module takes and, for a function, the type of value it returns.
  • By value: a change made to the parameter inside the module is not reflected in the calling module. By reference (BYREF): it is.
  • Declare variables inside the module, after the heading. Never use INPUT to replace a parameter.
  • RETURN, not OUTPUT. Return a value in every case: found and not found.
  • Efficient: use insert functions, return as soon as the answer is known, and add no steps the question does not ask for.

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. State what is meant by a function, and state one way in which it differs from a procedure.2 marks
    Answer
    1. A named module that returns a (single) value [1].
    2. A procedure does not return a value, whereas a function's call is used in an expression [1].

    Trap: Saying a function outputs a value; it returns it to the code that called it.

  2. A function has the header `FUNCTION Area(Width : REAL, Height : REAL) RETURNS REAL` and the call `Total ← Area(4.5, 2.0)`. Identify (a) the parameters, (b) the arguments and (c) the return type.3 marks
    Answer
    1. (a)
    2. `Width` and `Height` [1].
    3. (b)
    4. `4.5` and `2.0` [1].
    5. (c)
    6. REAL [1].

    Trap: Swapping the two terms: the parameters are in the header, the arguments are in the call.

  3. Write pseudocode for a procedure `Greet` that takes a name as a STRING parameter and outputs "Hello " followed by the name. Then write the statement that calls it for the name "Asha".4 marks
    Answer
    1. `PROCEDURE Greet(Person : STRING)` [1]
    2. `OUTPUT "Hello " & Person` [1]
    3. `ENDPROCEDURE` [1]
    4. `CALL Greet("Asha")` [1]

    Trap: Writing `INPUT Person` inside the procedure instead of using the parameter.

  4. Write pseudocode for a function `Perimeter` that takes the two side lengths of a rectangle, both REAL, and returns the perimeter as a REAL.3 marks
    Answer
    1. `FUNCTION Perimeter(Side1, Side2 : REAL) RETURNS REAL`: both parameters and the return type [1]
    2. `RETURN 2 * (Side1 + Side2)` [1]
    3. `ENDFUNCTION` [1]

    Trap: Ending with `OUTPUT 2 * (Side1 + Side2)`, which displays the value but returns nothing.

  5. `IsAdult(Age : INTEGER) RETURNS BOOLEAN` returns TRUE when Age is 18 or more. A person's age is stored in `Years`. Write an IF statement that outputs "Welcome" for an adult.3 marks
    Answer
    1. `IF IsAdult(Years) = TRUE THEN` [1]
    2. `OUTPUT "Welcome"` [1]
    3. `ENDIF` [1]

    Trap: Writing `CALL IsAdult(Years)` and then `IF RESULT = TRUE THEN`, as if a function were a procedure.

  6. The procedure `AddBonus(BYREF Score : INTEGER)` has the single statement `Score ← Score + 10`. The variable `Mark` holds 45. State the value of `Mark` after `CALL AddBonus(Mark)`. Explain your answer, and state the value of `Mark` if `BYREF` were removed.3 marks
    Answer
    1. `Mark` is 55 [1].
    2. By reference, the change made to `Score` inside the procedure is reflected in `Mark` in the calling code [1].
    3. Without `BYREF` the parameter is passed by value: the change is not reflected, so `Mark` stays 45 [1].

    Trap: Assuming a change to a parameter always changes the caller's variable; that happens only by reference.

  7. `Square(N : INTEGER) RETURNS INTEGER` returns N × N. `IsEven(N : INTEGER) RETURNS BOOLEAN` returns TRUE when N is even. `A` holds 3 and `B` holds 5. (a) Write one statement that stores `Square(A) + Square(B)` in `Total`. (b) Write an IF statement that outputs "Even" when `Total` is even. (c) State what is output.3 marks
    Answer
    1. (a)
    2. `Total ← Square(A) + Square(B)` [1]
    3. (b)
    4. `IF IsEven(Total) = TRUE THEN OUTPUT "Even" ENDIF` [1]
    5. (c)
    6. Total = 9 + 25 = 34, which is even, so "Even" is output [1].

    Trap: Writing the header in the call, as `Square(N : INTEGER)`, instead of just the argument.

  8. Write pseudocode for a function `Position` that takes a STRING `InString` and a CHAR `Target`. It returns the position of the first character of `InString` that equals `Target`, or -1 if there is none. Return as soon as the answer is known.6 marks
    Answer
    1. `FUNCTION Position(InString : STRING, Target : CHAR) RETURNS INTEGER` and `ENDFUNCTION` [1]
    2. `DECLARE Index : INTEGER` [1]
    3. Loop through the string: `FOR Index ← 1 TO LENGTH(InString)` [1]
    4. Extract and compare: `IF MID(InString, Index, 1) = Target THEN` [1]
    5. Immediate `RETURN Index` inside the loop [1]
    6. `RETURN -1` after the loop [1]

    Trap: Returning a value only when the character is found, so the function returns nothing when it is not.

  9. A library stores the titles of books on loan in a global 1D array `Loans` of 50 elements of type STRING. An unused element holds the empty string "". (a) Write pseudocode for a function `CountStart()` that takes a single character as its parameter and returns the number of titles in `Loans` that begin with that character. (b) Write one statement that outputs the total number of titles that begin with 'A' or 'E', using `CountStart()`.6 marks
    Answer
    1. (a)
    2. `FUNCTION CountStart(Letter : CHAR) RETURNS INTEGER` and `ENDFUNCTION` [1]
    3. `DECLARE Index, Count : INTEGER` and `Count ← 0` before the loop [1]
    4. `FOR Index ← 1 TO 50` ... `NEXT Index` [1]
    5. `IF LEFT(Loans[Index], 1) = Letter THEN Count ← Count + 1 ENDIF` in the loop [1]
    6. `RETURN Count` after the loop [1]
    7. (b)
    8. `OUTPUT CountStart('A') + CountStart('E')`: two calls in one expression, with no `CALL` [1]

    Trap: Naming the parameter `Char`, a data type, or ending with `OUTPUT Count` instead of `RETURN Count`: examiners reported both in this kind of function.

  10. A timing program stores two lap times, in seconds, in the INTEGER variables `LapA` and `LapB`. (a) Write pseudocode for a procedure `Order()` that is called with two INTEGER parameters. If the first is greater than the second, it swaps them, so that after the call the first argument holds the smaller value. (b) `LapA` holds 75 and `LapB` holds 68. A programmer leaves `BYREF` out of the header. State the values of `LapA` and `LapB` after `CALL Order(LapA, LapB)` and explain why. (c) State the values after the same call with `BYREF` in the header.7 marks
    Answer
    1. (a)
    2. `PROCEDURE Order(BYREF First : INTEGER, BYREF Second : INTEGER)` and `ENDPROCEDURE` [1]
    3. `DECLARE Temp : INTEGER` [1]
    4. `IF First > Second THEN` ... `ENDIF` [1]
    5. `Temp ← First`, `First ← Second`, `Second ← Temp` inside the IF [1]
    6. (b)
    7. `LapA` is still 75 and `LapB` is still 68 [1].
    8. The parameters are passed by value, so the swap made inside the procedure is not reflected in the arguments in the calling code [1].
    9. (c)
    10. `LapA` is 68 and `LapB` is 75 [1].

    Trap: Answering (b) with just 'it needs ByRef': examiners said that without explaining the effect on the calling code this does not gain full marks.

Say this, not that

Wording that loses the mark, against the wording the mark scheme credits.

Loses the markGets the mark
`OUTPUT MyString` as the last line of a function.`RETURN MyString`: a function returns a value to the code that called it.
`CALL Valid(MyString)` and then `IF RESULT = TRUE THEN`.`IF Valid(MyString) = TRUE THEN`: the return value replaces the call.
`INPUT` the values inside the procedure.Pass the values in as parameters and use them by name.
`FUNCTION MakeString(Count : INTEGER, Char : CHAR)`A parameter name cannot be a data type: use an identifier such as `AChar`, with the return type after `RETURNS`.

Frequently asked questions

What is the difference between a procedure and a function?
A function returns a single value with RETURN, and its header gives the return type after RETURNS. A function is used in an expression. A procedure carries out a task and does not return a value; it is run with CALL. OUTPUT only displays a value and does not give it to the code that made the call.
How do you call a function in an expression?
The return value replaces the call, so write IF Valid(MyString) = TRUE THEN. The call has the arguments only, with no types and no RETURNS. Writing CALL Valid(MyString) and then IF RESULT = TRUE THEN is invalid. Store the result of a function in a variable, or use the call directly in the expression.
What does BYREF do to a parameter?
BYREF passes the parameter by reference, so any change made to it inside the module is reflected in the value in the calling module. In AddBonus(BYREF Score : INTEGER), the statement Score ← Score + 10 changes Mark from 45 to 55. By value, the arguments used are unchanged, so Mark stays 45.
What is the difference between a parameter and an argument?
A parameter is a value that a procedure or function receives, named in the header with its data type, as in PROCEDURE Calculate(Expression : STRING). The argument is the value written in the call, as in CALL Calculate("34/7"). A procedure or function may have none, one or more parameters.
When should I write a procedure rather than repeat the same code?
Use a procedure where the same steps are needed in several places. Write them once as a module and replace each copy with a call. The module is designed and tested once, and any change needs to be made once only. The declaration of all variables used goes after the heading.
What mistake do students make when writing a function in pseudocode?
They use OUTPUT where RETURN is needed, so the value is displayed and not returned to the code that made the call. They also use a data type such as Char as an identifier, which is not allowed. Use RETURN in every route through the function, including both cases of an IF.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters