Study Guide

Procedures and Functions

How to split a program into named, reusable parts: procedures and functions, with and without parameters, CALL and RETURN, local and global variables, the library routines MOD, DIV, ROUND and RANDOM, and why this makes programs easier to maintain.

Lesson 5.9 Algorithms and Programming

For: Cambridge IGCSE Computer Science learners, or Key Stage 3 learners who have met loops and selection (about ages 13 to 14)

Stage: Think

The same lines, again and again

A fictional school programme-printing program shows two notices. Each is framed by the same line of dashes, which is typed out in full every time it is needed:

OUTPUT "-----"
OUTPUT "Spring Concert"
OUTPUT "-----"
OUTPUT "Tickets: 40"
OUTPUT "-----"

Think it through

The head teacher wants the line to be made of stars instead of dashes, and the real program has the line in thirty places. What is the problem? How could the program be arranged so that the change is made only once?

Show a model answer

Thirty places means thirty edits, and missing one leaves an inconsistent program. It is better to write the line once, give it a name and use the name wherever the line is needed. Then the change is made in one place.

Stage: Discover

Naming a set of instructions

A named block of instructions that a program can use whenever it needs it is a subroutine. One kind, which carries out a task, is a procedure. It is defined once, between PROCEDURE and ENDPROCEDURE, at the start of the program, and called with CALL wherever it is needed.

PROCEDURE DrawLine
  OUTPUT "-----"
ENDPROCEDURE

CALL DrawLine
OUTPUT "Spring Concert"
CALL DrawLine
OUTPUT "Tickets: 40"
CALL DrawLine

Defining a procedure does not run it. The program starts at the first line that is not inside a definition, and each CALL passes control to the procedure, which carries out its lines and then returns to the line after the call.

Following the program that uses DrawLine: the order of the output
OrderStatement carried out in the main programOUTPUT
1CALL DrawLine-----
2OUTPUT "Spring Concert"
3CALL DrawLine
4OUTPUT "Tickets: 40"
5CALL DrawLine

    Show the completed table
    OrderStatement carried out in the main programOUTPUT
    1CALL DrawLine-----
    2OUTPUT "Spring Concert"Spring Concert
    3CALL DrawLine-----
    4OUTPUT "Tickets: 40"Tickets: 40
    5CALL DrawLine-----

    The line of dashes is typed once, in the procedure. Changing it to stars changes all three places.

    Check your understanding

    What happens when the statement CALL DrawLine is carried out?
    Show the answer

    Answer: A. DrawLine’s lines are carried out, then the program carries on after the CALL.

    A procedure does nothing until it is called, and it can be called as many times as needed.

    Stage: Predict

    Giving a procedure something to work with

    Think it through

    A Welcome procedure is meant to show a different name each time it is used: “Welcome, Ravi”, then “Welcome, Chloe”. The lines inside it cannot be different each time. What must be different from one call to the next, and how could the procedure get it?

    Show a model answer

    The name has to be different, so the program must hand the name to the procedure each time it calls it. The procedure then uses whatever name it was given.

    A subroutine parameter, usually just called a parameter, is a variable in a subroutine’s definition that receives a value when the subroutine is called. It is written in brackets after the name, with its data type. The value supplied in the CALL is the argument.

    PROCEDURE Welcome(Name : STRING)
      OUTPUT "Welcome, ", Name
    ENDPROCEDURE
    
    CALL Welcome("Ravi")
    CALL Welcome("Chloe")

    The first call outputs Welcome, Ravi, because Name receives “Ravi”; the second outputs Welcome, Chloe. A procedure can have up to three parameters, separated by commas. The arguments are matched to the parameters in order, and must be of the right data types.

    PROCEDURE ShowTicket(Event : STRING, Row : INTEGER, Seat : INTEGER)
      OUTPUT Event, ": row ", Row, ", seat ", Seat
    ENDPROCEDURE
    
    CALL ShowTicket("Concert", 4, 12)
    CALL ShowTicket("Quiz", 1, 3)
    What each parameter holds on each call of ShowTicket
    CallEventRowSeatOUTPUT
    CALL ShowTicket("Concert", 4, 12)Concert
    CALL ShowTicket("Quiz", 1, 3)

      Show the completed table
      CallEventRowSeatOUTPUT
      CALL ShowTicket("Concert", 4, 12)Concert412Concert: row 4, seat 12
      CALL ShowTicket("Quiz", 1, 3)Quiz13Quiz: row 1, seat 3

      The procedure’s lines do not change between calls. Only the values in its parameters do.

      Do not confuse: Parameter and argument

      Where is it?Parameter
      In the definition: the named variable that receives a value.Name : STRING
      Where is it?Argument
      In the call: the actual value handed to the parameter."Ravi"

      Their names need not match: the argument is matched to a parameter by its place in the list, not by its name.

      Check your understanding

      A programmer writes CALL ShowTicket(12, 4, “Concert”) using the ShowTicket procedure above. What goes wrong?
      Show the answer

      Answer: C. They are matched by position, so 12 goes to Event, a STRING, and “Concert” to Seat, an INTEGER.

      Give the arguments in the same order, and of the same types, as the parameters.

      Stage: Discover

      A subroutine that gives back an answer

      A ticket costs 6 pounds. A booking program needs the cost of 3 tickets and the cost of 2 tickets, and then their total.

      Show a model answer

      No. OUTPUT puts the number on the screen, but the rest of the program never receives it. To be added to something else, the value must be handed back to the place in the program that asked for it.

      A subroutine that works out one value and hands it back is a function. The value it hands back is its return value. Its definition states the data type with RETURNS, and the keyword RETURN hands the value back.

      FUNCTION TicketCost(Tickets : INTEGER) RETURNS INTEGER
        RETURN Tickets * 6
      ENDFUNCTION
      
      Total ← TicketCost(3) + TicketCost(2)
      OUTPUT "Total: ", Total

      A function call is not a statement on its own: it is part of an expression. When the function reaches RETURN, the value it hands back replaces the call in the expression, and the expression is then worked out. A function is called without CALL.

      Working out Total ← TicketCost(3) + TicketCost(2)
      StepCallTicketsValue returned
      1TicketCost(3)3
      2TicketCost(2)
      3Total ← 18 + 12

        Show the completed table
        StepCallTicketsValue returned
        1TicketCost(3)318
        2TicketCost(2)212
        3Total ← 18 + 1230

        The program outputs Total: 30.

        Do not confuse: Procedure and function

        What does it do?Procedure
        Carries out a task. It does not hand back a value.CALL DrawLine
        What does it do?Function
        Works out one value and returns it, to be used in an expression.Total ← TicketCost(3) + 2

        A procedure is called with CALL, as a statement of its own. A function is never called with CALL: its call sits inside an expression, such as an assignment or an OUTPUT.

        Check your understanding

        Which line correctly uses the TicketCost function?
        Show the answer

        Answer: B. OUTPUT "Cost: ", TicketCost(4)

        A function call is used wherever its value is needed: in an output, an assignment, a condition or another call.

        1. State the job. Given two integers, hand back the larger. That is one value, so a function, with RETURNS INTEGER.
        2. Name the parameters. The two values are the parameters First and Second.
        3. Decide by comparison. If First is greater, the answer is First; otherwise it is Second. A local variable, Result, holds the choice.
        4. Return at the end. RETURN Result is the last statement.
        FUNCTION Larger(First : INTEGER, Second : INTEGER) RETURNS INTEGER
          DECLARE Result : INTEGER
          IF First > Second
            THEN
              Result ← First
            ELSE
              Result ← Second
          ENDIF
          RETURN Result
        ENDFUNCTION
        
        OUTPUT Larger(8, 13)
        Best ← Larger(Larger(4, 9), 6)
        OUTPUT Best

        Larger(8, 13) returns 13, so the first output is 13. In the second statement the inner call Larger(4, 9) returns 9 first, and then Larger(9, 6) returns 9, so Best is 9.

        Stage: Predict

        Who can see which variable?

        DECLARE Score : INTEGER
        
        PROCEDURE AddBonus(Points : INTEGER)
          DECLARE Bonus : INTEGER
          Bonus ← Points * 2
          Score ← Score + Bonus
        ENDPROCEDURE
        
        Score ← 0
        CALL AddBonus(3)
        CALL AddBonus(4)
        OUTPUT Score

        Think it through

        Predict what the program outputs. Then say whether a final line OUTPUT Bonus, added at the end of the program, would work, and why.

        Show what happens

        It outputs 14: the first call adds 3 × 2 = 6 and the second adds 4 × 2 = 8. OUTPUT Bonus would not work. Bonus is declared inside the procedure, so it only exists while the procedure is running, and the main program cannot use it.

        A local variable is declared inside a subroutine, and can be used only there. It is created when the subroutine runs and is gone when it ends. A global variable is declared outside every subroutine, and can be used in the whole program, including inside subroutines. Parameters are local to their subroutine too.

        Following Score and Bonus through the two calls
        MomentPointsBonusScore
        Before the first call-does not exist0
        In the first call3
        In the second call4
        After the second call-does not exist

          Show the completed table
          MomentPointsBonusScore
          Before the first call-does not exist0
          In the first call366
          In the second call4814
          After the second call-does not exist14

          The program outputs 14.

          Do not confuse: Local and global variables

          Where declared?Local variable
          Inside a subroutine. It can be used only there, and it disappears when the subroutine ends.Bonus in AddBonus
          Where declared?Global variable
          Outside all subroutines. Every part of the program can use it, and it lasts as long as the program runs.Score

          Prefer local variables and parameters: a subroutine that uses only its own can be reused, and cannot change something else by accident.

          DECLARE Level : INTEGER
          
          PROCEDURE Reset
            DECLARE Level : INTEGER
            Level ← 0
          ENDPROCEDURE
          
          Level ← 5
          CALL Reset
          OUTPUT Level

          Here a local variable has the same name as a global one.

          Apply it

          What does this program output?
          Show the answer

          Answer: D. 5, because Reset changes its own local Level, not the global one.

          Two variables can share a name if they are declared in different places, but they are not the same variable.

          Stage: Discover

          Subroutines that come ready-made

          Think it through

          A calculator shows 7.456. Predict the number you get when you round it to 1 decimal place, and to 0 decimal places (a whole number).

          Show what happens

          To 1 decimal place it is 7.5, because the next digit, 5, rounds the 4 up. To 0 decimal places it is 7, because the next digit, 4, rounds down.

          A library routine is a subroutine that is already written and ready to use, so that you do not write it yourself. The syllabus names four. DIV(a, b) is the whole number of times b goes into a, and MOD(a, b) is the remainder, as in Lesson 3. ROUND(value, places) rounds a number to a number of decimal places. RANDOM() returns a random number between 0 and 1.

          Working out library routine results
          ExpressionResult
          DIV(17, 5)3
          MOD(17, 5)
          ROUND(3.14159, 2)
          ROUND(7.456, 1)
          ROUND(9.7, 0)

            Show the completed table
            ExpressionResult
            DIV(17, 5)3
            MOD(17, 5)2
            ROUND(3.14159, 2)3.14
            ROUND(7.456, 1)7.5
            ROUND(9.7, 0)10

            The first row is given as an example.

            1. State the job. Show a number of minutes as whole hours and the minutes left over.
            2. Choose the routines. “Whole hours” is a DIV by 60, and “left over” is a MOD by 60.
            3. Write the procedure with one parameter.
            PROCEDURE ShowDuration(Minutes : INTEGER)
              OUTPUT DIV(Minutes, 60), " h ", MOD(Minutes, 60), " min"
            ENDPROCEDURE
            
            CALL ShowDuration(130)

            DIV(130, 60) is 2 and MOD(130, 60) is 10, so the output is 2 h 10 min.

            A dice-rolling game needs a random whole number from 1 to 6. RANDOM() gives a number from 0 to 1, so RANDOM() * 5 gives a number from 0 to 5; ROUND of that is a whole number from 0 to 5, and adding 1 shifts the range to 1 to 6.

            Die ← ROUND(RANDOM() * 5, 0) + 1

            Check your understanding

            What are the smallest and largest values that Die ← ROUND(RANDOM() * 5, 0) + 1 can hold?
            Show the answer

            Answer: B. 1 and 6, because ROUND gives 0 to 5 and 1 is added.

            Work out the smallest and largest value of each part, then combine them.

            Stage: Explain

            Programs that are easy to change

            Think it through

            Think back to the school notices in step 1 and the TicketCost function. Give two reasons why a program built from subroutines is easier to look after than one long list of lines.

            Show a model answer

            Good reasons are: a change is made in one place, not in every copy; each subroutine can be tested and understood on its own; a name such as TicketCost tells the reader what a part is for; a subroutine can be reused in other programs; and different people can write different subroutines at once.

            A program that is easy to understand and change later is maintainable. The syllabus links this to four habits: procedures and functions to avoid repeating code; meaningful identifiers for variables, constants, arrays, procedures and functions; comments (// in pseudocode) that explain what a section is for; and neat layout with indentation.

            // Cost in pounds of a number of tickets, at 6 pounds each
            FUNCTION TicketCost(Tickets : INTEGER) RETURNS INTEGER
              RETURN Tickets * 6
            ENDFUNCTION

            Check your understanding

            A program uses the identifiers X, Y and Z, with no comments. Which change makes it most maintainable?
            Show the answer

            Answer: C. Renaming X, Y and Z to TicketCount, TicketPrice and TotalCost, with comments.

            Maintainable means that someone else, or you in six months’ time, can understand it quickly.

            Stage: Apply

            Spot the mistake

            Sam (fictional) wants a function that doubles a number, and a line that uses it. The line that adds 1 outputs nothing sensible.

            FUNCTION Double(Number : INTEGER) RETURNS INTEGER
              OUTPUT Number * 2
            ENDFUNCTION
            
            Answer ← Double(7) + 1
            OUTPUT Answer

            Apply it

            What is wrong with Sam’s function, and how is it fixed?
            Show the answer

            Answer: A. It shows the doubled number but never returns it, so replace OUTPUT with RETURN.

            A function that does not return a value gives its caller nothing to use.

            Stage: Apply

            Write one yourself

            A fictional cinema charges by age: under 12 pays 5 pounds, 65 or over pays 6, and everyone else pays 8. A visitor’s age decides the price.

            Think it through

            Write a function TicketPrice that takes an age and returns the price. Then write the rest of a program that reads the ages of 3 visitors and outputs the total. Say what it outputs for ages 9, 70 and 30.

            Show a model answer
            FUNCTION TicketPrice(Age : INTEGER) RETURNS INTEGER
              DECLARE Price : INTEGER
              IF Age < 12
                THEN
                  Price ← 5
                ELSE
                  IF Age >= 65
                    THEN
                      Price ← 6
                    ELSE
                      Price ← 8
                  ENDIF
              ENDIF
              RETURN Price
            ENDFUNCTION
            
            Total ← 0
            FOR Visitor ← 1 TO 3
              INPUT Age
              Total ← Total + TicketPrice(Age)
            NEXT Visitor
            OUTPUT "Total: ", Total

            For 9, 70 and 30 the prices are 5, 6 and 8, so the program outputs Total: 19. The function is defined first, and it is called inside the loop as part of an expression.

            Go deeper The same ideas in Python
            import random
            
            def draw_line():
                print("-----")
            
            def show_ticket(event, row, seat):
                print(f"{event}: row {row}, seat {seat}")
            
            def ticket_price(age):
                if age < 12:
                    price = 5
                elif age >= 65:
                    price = 6
                else:
                    price = 8
                return price
            
            score = 0
            
            def add_bonus(points):
                global score
                bonus = points * 2
                score = score + bonus
            
            total = 0
            for visitor in range(3):
                age = int(input())
                total = total + ticket_price(age)
            print("Total:", total)
            print(17 // 5, 17 % 5, round(3.14159, 2))
            die = round(random.random() * 5) + 1
            • Python has one keyword, def, for both. A subroutine that uses return is a function; one that does not is a procedure. There is no CALL: both are called by writing the name and the brackets, draw_line().
            • Parameters are written without data types, in brackets after the name.
            • A variable given a value inside a function is local. To change a global variable you have to say so with global score; without it, score = ... would make a new local variable.
            • // is DIV and % is MOD. round(x, places) is ROUND, but when a number ends exactly in 5 Python rounds to the nearest even digit, so do not rely on exact halves. random.random() gives a number from 0 up to, but not including, 1.
            • ROUND(RANDOM() * 5, 0) + 1 gives 1 and 6 only half as often as 2 to 5, because only half of the range rounds to them. random.randint(1, 6) gives each of 1 to 6 equally often, which is what a fair dice needs.

            Stage: Consolidate

            Show what you know

            Think it through

            Explain to a friend the difference between a procedure and a function, and between a parameter and an argument. Use the cinema or the concert as your example.

            Show a model answer

            A good answer says a procedure carries out a task and is called with CALL, such as showing a ticket, while a function works out a value and returns it with RETURN, such as TicketPrice(30) giving 8, so its call is used in an expression. A parameter is the named variable in the definition (Age), and an argument is the actual value given in the call (30), matched by position.

            Apply it

            A fictional library program needs to show a heading in the same style in many places, and to work out the fine for a book that is a given number of days late. Which pair of subroutines is the best choice?
            Show the answer

            Answer: C. A procedure for the heading, because it shows something, and a function for the fine.

            Choose a procedure when the subroutine does something, and a function when it works something out.

            • A subroutine is a named, reusable block. A procedure carries out a task and is called with CALL. A function returns one value (RETURNS, RETURN) and is called inside an expression, without CALL.
            • A parameter is the variable in the definition; an argument is the value in the call. Arguments are matched to parameters by position and type. A subroutine may have up to three parameters.
            • A local variable exists only inside its subroutine; a global variable can be used everywhere. A local variable with the same name as a global one is a separate variable.
            • Library routines are ready-made: DIV and MOD for whole number and remainder, ROUND for decimal places, RANDOM for a random number from 0 to 1.
            • Subroutines, meaningful names and comments make a program maintainable: a change is made in one place and each part can be understood alone.
            • Usual faults: calling a function with CALL, forgetting RETURN, giving arguments in the wrong order, and using a local variable outside its subroutine.

            Sources and scope

            • What this lesson is. The ninth lesson of the Algorithms and Programming module, written for this site. It covers points 8.1.6 and 8.1.7 of Cambridge IGCSE Computer Science 0478 (2026 to 2028, version 6) and part of 8.1.8. Its curriculum links are provisional and imply no review or endorsement by any examination board.
            • Original material. The school programme notices, the ticket booking, the cinema, the library and Sam are fictional, written for this lesson. The pseudocode follows the layout of the syllabus’s pseudocode guide (definitions at the start, CALL for procedures only), and every output was worked out by hand and checked with an equivalent Python program.
            • Simplified on purpose. Parameters are passed as values only; passing by reference is not part of 0478. Each function has a single RETURN at the end. The exact rules for a local variable with the same name as a global one differ between languages; the lesson shows the usual behaviour, and the pseudocode guide does not describe it.
            • Left to later lessons. Arrays as parameters and return values, and recursion, are not taught here. Arrays are in Lesson 10.