Teachers' Portal  /  A-Level Computer Science 9618  /  Programming  /  Procedures and functions
Lesson pack · A-Level Computer Science 9618 · 11.3 · AS Level

Procedures and functions

Write it once, call it often. Structured programs are built from small named subroutines.

Student lesson Lab, full screen
At a glance

The shape of the lesson

Topic
Programming
Syllabus reference
Cambridge International AS and A Level Computer Science 9618, 11.3
Level
AS Level
Duration
45 minutes, lab-led; stretches to a 60 minute block (see the contingency notes)
Position in topic
Lesson 3 of 4 in Programming; follows Selection and iteration constructs; leads into Passing parameters by value and by reference
Central model
Fig. 1: control passes to the subroutine and back; only a function brings a value back with it
Cooperative structure
Assessment
Stage 1 check and the exam-style plenary from the student lesson, plus the worksheet as the exit task
Learning objectives

By the end of the lesson, learners can

Section by section
  • Defining a procedure: Use a procedure when a task is needed in more than one place, or to break a large problem into separate modules, and the task does not need to hand back a single value (it outputs something, or changes data).
  • Defining a function: Use a function when the subroutine must work out one value for the code that calls it.
  • The terminology: Questions often show a subroutine and ask you to identify its parts, so learn these words precisely.
Key points to leave on the board
  • Procedure: PROCEDURE Name(...) ... ENDPROCEDURE; run with CALL Name(...).
  • Function: header ends RETURNS type; uses RETURN; used inside an expression, never with CALL.
  • Parameter is in the header; argument is in the call; they match in number, order and type.
  • Efficient: stop loops early, do not repeat calculations, replace copied code with a subroutine.
The core visual model

One picture every idea returns to

A procedure is a named block of code that performs a task; it may have none, one or more parameters and is run with a CALL statement. A function also performs a task but returns a single value: its header ends RETURNS data type, it uses RETURN, and it is used inside an expression, where the return value replaces the call. The values passed in a call are arguments; the identifiers in the header that receive them are parameters. Subroutines give modular, reusable code that is easier to test and maintain.

a procedure call is a statement; a function call is part of an expression main program Total ← 10 CALL ShowLine(5, '*') Total ← Total + Square(4) OUTPUT Total PROCEDURE ShowLine(...)builds and outputs *****ENDPROCEDURE FUNCTION Square(N ...)RETURN N * NENDFUNCTION returns control only 16 replaces the call: Total = 26
Fig. 1: control passes to the subroutine and back; only a function brings a value back with it
Lesson sequence

Forty-five minutes, phase by phase

TimePhaseWhat happens in the roomGrouping
0 to 5 minHook: predictOpen with the question in the title, Write it once, call it often.. Structured programs are built from small named subroutines. Put the figure on the board: it is the one picture every idea in the lesson returns to.Whole class, then pairs
5 to 13 minTeach and check: Defining a procedureUse a procedure when a task is needed in more than one place, or to break a large problem into separate modules, and the task does not need to hand back a single value (it outputs something, or changes data). Project tab 5 of the lab (Procedures and functions) and let a student drive it while the class predicts. Model the worked example Follow the calls on the board, one line at a time. Your turn: Write the statement that outputs a row of 12 hyphens using ShowLine.Whole class, then pairs
13 to 21 minTeach and check: Defining a functionUse a function when the subroutine must work out one value for the code that calls it. Model the worked example Trace a function call on the board, one line at a time. Your turn: What does CountChar("Mississippi", 's') return?Pairs
21 to 30 minTeach and check: The terminologyQuestions often show a subroutine and ask you to identify its parts, so learn these words precisely. Model the worked example Make it efficient on the board, one line at a time. Your turn: In Floor ← Area(4.0, 2.5), identify the arguments and give the return value, assuming Area returns Length * Width.Mix-Pair-Share
30 to 36 minCheckThe four Stage 1 questions from the student lesson, answered on mini whiteboards or by show of fingers. Re-teach the one most get wrong.Individual, then whole class
36 to 43 minPlenaryThe exam-style questions from Stage 2, one at a time: thirty seconds alone, then a random call. The feedback lines in the key give the examiner's wording.Individual, random call
43 to 45 minExit and homeworkSet the worksheet below (6 questions, 21 marks). Learners self-assess against the objectives before they leave.Individual
Timing and contingency

Protect the parts that carry the learning

The sequence carries about fifty minutes of material, so the lab is driven by one student while the class predicts rather than explored freely. Times are a guide.

Protected: the check at 30 minutes. It is the only individual read on whether the key idea landed, and it is not cut.

Cut first if the build overruns: the last check in The terminology, never the check or the plenary.

In a 60 minute block: run worksheet questions 1 to 3 in class as a Rally Coach set and model both the hardest worked example and its check live.

Running the cooperative task

Mix-Pair-Share

Students mix around the room until you call pair; they pair with the nearest classmate, discuss the prompt, then mix again. Three prompts of rising difficulty, three different partners.

The full structure, with its variations and the other twelve, is on the cooperative-learning page.

Examiner traps to pre-empt

What to head off, and how

Trap learners fall intoTeaching move that pre-empts it
A procedure does not return a value, so X ← ShowLine(5, '*') is wrong.If the main program needs a result back, write a function instead.
CALL CountChar("banana", 'a') loses the mark: a function is never CALLed, and its return value would be thrown away.Return to Defining a function: ask a pair to state the correct version and show it on the lab before moving on.
Do not mix up parameter and argument.The parameter is the name in the header (Length); the argument is what is passed in the call (4.0).
Worksheet

Procedures and functions: worksheet

6 questions, 21 marks. Written in the style of the papers; no past paper question is reproduced.

NameClassDate
Q1 · recall[3 marks]

Explain what is meant by each term: (a) parameter (b) argument (c) return value.

Q2 · explain[3 marks]

A large program is being written by a team. Explain three benefits of writing it as a set of procedures and functions.

Q3 · trace[4 marks]

Study this function.

FUNCTION Mystery(N : INTEGER) RETURNS INTEGER
    DECLARE Result : INTEGER
    Result ← 0
    WHILE N > 0
        Result ← Result + (N MOD 10)
        N ← N DIV 10
    ENDWHILE
    RETURN Result
ENDFUNCTION

(a) Trace Mystery(4073). (b) State the output of OUTPUT Mystery(4073) * 2. (c) Describe the purpose of the function.

Q4 · write[4 marks]

Write a function MaxOfThree that takes three integer parameters and returns the largest.

Q5 · write[4 marks]

Write a procedure TimesTable that takes an integer parameter and outputs its multiplication table from 1 times to 12 times, one line each, for example 7 x 3 = 21. Then write a statement that uses it to output the 7 times table.

Q6 · analysis[3 marks]

A function checks whether a code is in an array of 500 codes. It uses a FOR loop from 1 to 500, sets Found ← TRUE when the code matches, and returns Found after the loop. Explain how the function could be made more efficient, and why this is better.

Answer key and marking notes
Q1 · 3 marks
  • (a) An identifier in the procedure or function header that receives a value passed to the subroutine.
  • (b) The actual value (or variable) passed to the subroutine when it is called.
  • (c) The single value a function sends back to the calling code, which replaces the function call in the expression.
Q2 · 3 marks
  • Each subroutine can be written and tested separately, possibly by different programmers.
  • Code that is needed in several places is written once and called many times, so the program is shorter.
  • Maintenance is easier: a change or fix is made in one subroutine only; subroutines can also be reused in other programs (any three).
Q3 · 4 marks
  • N 4073, Result 3; N 407, Result 10; N 40, Result 10; N 4, Result 14; N 0, loop ends.
  • Mystery(4073) returns 14.
  • (b) 14 * 2 = 28 is output.
  • (c) It returns the sum of the digits of N.
Q4 · 4 marks
  • Header: FUNCTION MaxOfThree(A : INTEGER, B : INTEGER, C : INTEGER) RETURNS INTEGER.
  • Max ← A, then IF B > Max THEN Max ← B ENDIF.
  • IF C > Max THEN Max ← C ENDIF.
  • RETURN Max and ENDFUNCTION.
Q5 · 4 marks
  • PROCEDURE TimesTable(Number : INTEGER) ... ENDPROCEDURE, with Count declared locally.
  • FOR Count ← 1 TO 12 ... NEXT Count.
  • OUTPUT Number, " x ", Count, " = ", Number * Count inside the loop.
  • CALL TimesTable(7).
Q6 · 3 marks
  • Use a conditional loop (WHILE / REPEAT) that stops when the code is found or the end of the array is reached, or RETURN TRUE as soon as a match is found.
  • Fewer comparisons are made when the code is found early, for example 1 instead of 500 if it is the first element.
  • So the function runs faster on average; it still returns FALSE after checking all 500 if the code is not there.
Quiz

6 multiple-choice questions on this lesson

From the topic question bank. Assign them in the app for a marked score in your gradebook, or run the topic as a class game.

Q11 mark

Which header correctly defines a subroutine that takes a string and returns the number of vowels in it?

  • AFUNCTION CountVowels(Word : STRING) RETURNS INTEGER
  • BPROCEDURE CountVowels(Word : STRING) RETURNS INTEGER
  • CFUNCTION CountVowels(Word : STRING) RETURNS
  • DFUNCTION CountVowels(Word : INTEGER) RETURNS STRING
Q21 mark

A function has the header FUNCTION Fee(Days : INTEGER, Rate : REAL) RETURNS REAL and is used in Cost ← Fee(3, 12.5). What are Days and Rate?

  • AParameters
  • BArguments
  • CReturn values
  • DGlobal variables
Q31 mark

A program contains PROCEDURE Greet(Name : STRING) and FUNCTION Square(N : INTEGER) RETURNS INTEGER. Which statement is valid?

  • AOUTPUT Square(4) + 1
  • BCALL Square(4)
  • CX ← Greet("Sam")
  • DCALL Greet()
Q41 mark

What is output by the last line?

FUNCTION Product(N : INTEGER) RETURNS INTEGER
    DECLARE P : INTEGER
    DECLARE Index : INTEGER
    P ← 1
    FOR Index ← 1 TO N
        P ← P * Index
    NEXT Index
    RETURN P
ENDFUNCTION

OUTPUT Product(4) - Product(3)

  • A18
  • B1
  • C24
  • D6
Q51 mark

Data is a global ARRAY[1:6] OF INTEGER holding 4, 11, 7, 15, 20, 9 in that order.

FUNCTION FirstOver(Limit : INTEGER) RETURNS INTEGER
    DECLARE Index : INTEGER
    Index ← 1
    WHILE Index <= 6
        IF Data[Index] > Limit THEN
            RETURN Index
        ENDIF
        Index ← Index + 1
    ENDWHILE
    RETURN -1
ENDFUNCTION

OUTPUT FirstOver(10) + FirstOver(30)
What is output?

  • A1
  • B10
  • C4
  • D2
Q61 mark

Prices is a global ARRAY[1:500] OF REAL and TaxRate is a global REAL.

FUNCTION AddTax(Count : INTEGER) RETURNS REAL
    DECLARE Total : REAL
    DECLARE Index : INTEGER
    Total ← 0
    FOR Index ← 1 TO Count
        Total ← Total + Prices[Index] * (1 + TaxRate / 100)
    NEXT Index
    RETURN Total
ENDFUNCTION
Which change makes the function more efficient without changing its result?

  • AWork out 1 + TaxRate / 100 once before the loop, store it in a local variable and use that inside the loop
  • BReplace the FOR loop with a REPEAT loop that still runs once for each of the Count prices
  • CDeclare Total and Index as global variables instead of declaring them inside the function
  • DCopy the body of the function into the main program at every place where AddTax is called
Quiz key
Q1: A

A subroutine that returns one value is a function: FUNCTION, the name, typed parameters, then RETURNS and the type of the value returned (a count is an INTEGER). A procedure never has RETURNS. A header ending in RETURNS with no type is incomplete. The last header has the two data types the wrong way round.

Q2: A

Identifiers in the header that receive values are parameters. The values passed in the call, 3 and 12.5, are the arguments. The return value is the single REAL that replaces Fee(3, 12.5) in the expression. Days and Rate exist only inside the function, so they are not global variables.

Q3: A

Square(4) returns 16, which replaces the call in the expression, so 17 is output. A function is never run with CALL. Greet is a procedure, so it returns no value to assign to X. CALL Greet() passes no argument, but Greet needs one STRING parameter.

Q4: A

Product(4) = 1 × 2 × 3 × 4 = 24 and Product(3) = 1 × 2 × 3 = 6, so 24 − 6 = 18 is output. 1 subtracts the arguments (4 − 3) instead of the return values. 24 and 6 are the two return values on their own.

Q5: A

FirstOver(10) returns 2, the index of 11, the first element over 10, and stops at once. No element is over 30, so the loop ends and -1 is returned. 2 + (−1) = 1. The output 10 adds the value 11 instead of its index. 4 assumes the loop carries on to the last match (index 5). 2 ignores the -1 returned by the second call.

Q6: A

1 + TaxRate / 100 is the same on every pass, so working it out once saves a division and an addition each time round the loop. A REPEAT loop running the same number of times does the same work. Making the variables global saves nothing and risks clashes with other code. Copying the code into several places makes the program longer and harder to maintain, the opposite of efficient pseudocode.

Lab and demo

What to project

The student lesson embeds these tabs. Open them full screen on the projector; every slider has a drag handle on the stage.

Slides

Slides for this lesson

A projectable deck for every pack is on the way. Until then, present the student lesson full screen: its sections, figure and lab tabs follow the same order as the plan above.

Also for this topic

Everything else you can use

Original work by the TheLucidSTEM team. The worksheet items are written in the style of the papers; no past paper question is reproduced.
Previous lessonSelection and iteration constructs