SYLLABUS 8.1.6 · PAPER 2 · ALSO FOR 0984 AND 2210

Procedures, functions, parameters and variable scope

Procedures and functions let you write a piece of code once, give it a name, and use it wherever it is needed. The difference between them, and what parameters and scope mean, come up often.

Procedures and functions

A procedure is a named block of code that does a task. It is run with CALL. A function is a named block of code that returns a single value. It is used inside an expression, such as an assignment or an OUTPUT, and must have RETURNS for its type and a RETURN statement.

PROCEDURE ShowLine(Length : INTEGER)
    DECLARE Count : INTEGER
    DECLARE Line : STRING
    Line <- ""
    FOR Count <- 1 TO Length
        Line <- Line & "-"
    NEXT Count
    OUTPUT Line
ENDPROCEDURE

FUNCTION Grade(Mark : INTEGER) RETURNS STRING
    IF Mark >= 70 THEN
        RETURN "Merit"
    ELSE
        RETURN "Pass"
    ENDIF
ENDFUNCTION

CALL ShowLine(10)
OUTPUT Grade(82)

Parameters

A parameter is a value passed into a procedure or function when it is called. In the definition it is listed with its data type, as in Mark : INTEGER. When it is called, a value is supplied for it: Grade(82).

Local and global variables

A local variable is declared inside a procedure or function and can only be used there. It disappears when the routine finishes. A global variable is declared in the main program and can be used anywhere. Local variables are safer: code elsewhere can’t change them by accident, and the same name can be reused in different routines.

Where marks go

  • Saying a function “outputs” a value: it returns one to the code that called it.
  • Writing a function with no RETURN, or a procedure that tries to return a value.
  • Calling a function with CALL, or a procedure inside an expression.
  • Leaving out the data type of a parameter or of the value a function returns.
  • Using a local variable outside the routine where it was declared.

Try a question

5 MARKS · MARKED ON THIS PAGE

A school awards grades for a test marked out of 100. Write pseudocode that: - defines a function Grade(Mark : INTEGER) RETURNS STRING that returns "A" for a mark of 70 or more, "B" for 50 to 69, "C" for 30 to 49 and "U" for a mark below 30 - in the main program, uses a count-controlled loop to input exactly 5 marks, one at a time, into the variable Mark - for each mark, outputs the grade returned by Grade(Mark) on its own line (just the letter) - uses the variable FailCount to count how many of the 5 marks get the grade U - after the loop, outputs the message Fails: followed by the value of FailCount, for example OUTPUT "Fails: ", FailCount

solutionPseudocode
Loading...
Type your answer first.