CIE IGCSE | 8.1.6B.2 Define and Call Functions

Lesson objective

Define and call functions with and without parameters, return a value of the declared type, and trace how that result is used in the calling expression.

Learn

8.1.6B.2 | DEFINE AND CALL FUNCTIONS

01 | THE CALLER NEEDS A VALUE

Imagine a ticket program that needs to calculate a cost, compare it with a budget and display it later. A procedure that merely displays the cost cannot supply a result for those calculations. The caller needs the value itself.

A function is a named routine that returns a single value to the point where it is called. A routine is a named group of instructions performing a task. A function call is used within an expression: values and operations evaluated to produce a result.

Think of the call as a request for a result. The function executes its instructions, returns the result, and the calling expression continues using that value.

02 | DEFINE A FUNCTION AND ITS RESULT TYPE

A definition states what the function does. Begin with FUNCTION, its name, any parameters, and RETURNS followed by the result’s data type. Finish with ENDFUNCTION.

A parameter is a named item receiving a supplied value at a call. Number is an INTEGER parameter. The body is the instruction group between FUNCTION and ENDFUNCTION; here it contains RETURN Number * 2.

RETURNS INTEGER declares the result type in the header. RETURN supplies the actual result from the body. These keywords have different jobs.

FUNCTION Double(Number : INTEGER) RETURNS INTEGER
  RETURN Number * 2
ENDFUNCTION

03 | CALL IT INSIDE AN ASSIGNMENT

In Cambridge pseudocode, a function call belongs in an expression. Do not put CALL before it: CALL invokes a procedure as a complete statement.

At Double(6), six is supplied to Number. RETURN evaluates six times two and sends twelve back. The call is replaced by twelve in the right-hand expression, and the assignment stores twelve in Result.

The definition is placed at the start of the code. Merely defining Double does not perform the calculation; the expression containing the call causes execution of its body.

FUNCTION Double(Number : INTEGER) RETURNS INTEGER
  RETURN Number * 2
ENDFUNCTION

DECLARE Result : INTEGER
Result ← Double(6)
OUTPUT Result

04 | TRACE THE CALL AND ITS RESULT

The caller is the part of the program making the call. The argument is the value or expression supplied by that caller, also described as a parameter value.

The caller must receive the function’s result before it can finish this assignment. Result is not assigned six simply because six appears in the call. Six is the incoming value; twelve is the returned value.

Incoming argument and returned result have different roles
StageWhat happens
Caller reaches Double(6)The argument value is 6
Function startsParameter Number receives 6
Body evaluates Number * 2The calculation produces 12
RETURN executes12 is returned to the calling expression
Assignment finishesResult receives 12
OUTPUT ResultThe stored value 12 is displayed

05 | USE THE RESULT IN A LARGER EXPRESSION

The returned value need not be stored on its own. It can become part of a larger calculation. For Total ← Double(6) + 3, Double returns twelve, then the caller adds three and stores fifteen.

A call can also appear in an OUTPUT expression. OUTPUT Double(4) displays eight. The display comes from the caller’s OUTPUT instruction, not from RETURN.

Repeated calls are separate executions. Double(6) and Double(4) run the same definition with different arguments.

DECLARE Total : INTEGER
Total ← Double(6) + 3
OUTPUT Total
OUTPUT Double(4)

06 | RETURN IS NOT OUTPUT

RETURN provides a result to the caller. OUTPUT communicates information to the user. Returning a value does not itself display it, and displaying a number does not replace the required RETURN in a function.

RETURN ends the current function execution and hands back its result. It does not stop the whole program. The caller continues evaluating the expression that requested the value.

A function that returns a cost can be used even when no display is wanted. The caller might compare the result with a budget or add it to another cost.

Return, assignment and output are separate operations
InstructionEffect
RETURN Quantity * PriceProvides the calculated value to the caller
Cost ← TicketCost(3, 4.50)Stores the returned value
OUTPUT CostDisplays the stored value

07 | MATCH PARAMETERS AND ARGUMENTS

TicketCost needs an INTEGER quantity and a REAL price. The argument positions determine which values belong to which parameters. Its REAL result can be stored in a REAL variable.

TicketCost(3, 4.50) returns 13.5. The caller can supply literals, variables or suitable expressions. With Tickets equal to two, TicketCost(Tickets + 1, 4.50) first evaluates the argument expression to three and returns the same cost.

Match the number, order and types of arguments to the definition. The syllabus permits functions with up to three parameters. A parameter list does not automatically validate that a quantity or price is non-negative; these examples assume suitable inputs.

FUNCTION TicketCost(Quantity : INTEGER, Price : REAL) RETURNS REAL
  RETURN Quantity * Price
ENDFUNCTION

DECLARE Tickets : INTEGER
DECLARE Cost : REAL
Tickets ← 2
Cost ← TicketCost(Tickets + 1, 4.50)

08 | TRY A FUNCTION INSIDE A CALCULATION

Choose a quantity, price and delivery charge. The caller evaluates Total ← TicketCost(Quantity, Price) + Delivery. Predict the returned ticket cost separately from the caller’s final total.

The controls validate the demo’s values. Prices and charges are displayed to two decimal places for readability; formatting is separate from the numeric result returned by the pseudocode function.

    09 | A FUNCTION CAN RETURN BOOLEAN

    Not every useful result is a number. IsValidScore returns TRUE or FALSE for an INTEGER score. The AND expression itself produces the BOOLEAN value returned.

    The caller uses that result as its IF condition. For fifty, both comparisons are TRUE, so the caller outputs “Score accepted”. For one hundred and one, the upper comparison is FALSE, so the caller outputs “Score rejected”.

    The function checks only the numeric range. Its INTEGER parameter assumes an integer has already been supplied; it does not convert arbitrary input text.

    FUNCTION IsValidScore(Score : INTEGER) RETURNS BOOLEAN
      RETURN (Score >= 0) AND (Score <= 100)
    ENDFUNCTION
    
    IF IsValidScore(50)
      THEN
        OUTPUT "Score accepted"
      ELSE
        OUTPUT "Score rejected"
    ENDIF

    10 | RETURN A RESULT ON EVERY POSSIBLE ROUTE

    A function with selection must provide a result whichever route is taken. GradeLabel returns a STRING describing a valid score from zero to one hundred.

    There is one RETURN in each final branch. A call returns only the value on the selected route: eighty returns “Distinction”, fifty returns “Pass”, and forty-nine returns “Not a pass”. “Single returned value” does not mean a definition may contain only one RETURN instruction.

    These returns cover all possible paths through the selection. Omitting the lowest branch’s RETURN would leave some calls without the required result.

    FUNCTION GradeLabel(Score : INTEGER) RETURNS STRING
      IF Score >= 80
        THEN
          RETURN "Distinction"
        ELSE
          IF Score >= 50
            THEN
              RETURN "Pass"
            ELSE
              RETURN "Not a pass"
          ENDIF
      ENDIF
    ENDFUNCTION
    
    OUTPUT GradeLabel(79)

    11 | A FUNCTION MAY HAVE NO PARAMETERS

    A function does not have to receive arguments. It still returns a value. StandardTicketPrice below supplies a fixed REAL value without needing information from the caller.

    Cambridge’s no-parameter definition uses the name followed by RETURNS and the result type. The no-parameter function call uses its name as part of an expression, as shown below.

    This example is useful for learning the notation. For a simple fixed rule, a named constant may be a simpler design choice. Having no parameters does not make this a procedure: the function still supplies a returned value.

    FUNCTION StandardTicketPrice RETURNS REAL
      RETURN 4.50
    ENDFUNCTION
    
    DECLARE Price : REAL
    Price ← StandardTicketPrice
    OUTPUT Price

    12 | A FUNCTION BODY CAN INCLUDE A LOOP

    A function can do more than one arithmetic instruction. SumTo adds every INTEGER from one to Limit, then returns the total. Assume Limit is a non-negative INTEGER.

    Total is initialised to zero each time the function runs. With Limit three, its values become one, three and six, so the result is six. With Limit zero, the ascending FOR has no iterations and the function returns zero.

    RETURN is after NEXT, so the complete loop finishes before the result is returned. Putting RETURN inside the loop would end the function during its first iteration rather than calculate the full total.

    FUNCTION SumTo(Limit : INTEGER) RETURNS INTEGER
      DECLARE Counter : INTEGER
      DECLARE Total : INTEGER
      Total ← 0
      FOR Counter ← 1 TO Limit
        Total ← Total + Counter
      NEXT Counter
      RETURN Total
    ENDFUNCTION
    
    OUTPUT SumTo(3)

    13 | THREE PARAMETERS, ONE RETURNED RESULT

    Three INTEGER scores can be supplied to a mean function. The returned mean uses REAL because dividing whole numbers can produce a fractional result.

    For scores two, four and nine, the sum is fifteen and the mean is five. For two, four and eight, the result is fourteen divided by three, approximately 4.667. The function does not round or format that value.

    The parentheses make the calculation explicit: add all three scores before dividing by three. Writing First + Second + Third / 3 would divide only the third score before adding the others.

    FUNCTION MeanScore(First : INTEGER, Second : INTEGER, Third : INTEGER) RETURNS REAL
      RETURN (First + Second + Third) / 3
    ENDFUNCTION
    
    DECLARE Average : REAL
    Average ← MeanScore(2, 4, 9)
    OUTPUT Average

    14 | FIX COMMON FUNCTION ERRORS

    Using CALL: write Cost ← TicketCost(3, 4.50), not CALL TicketCost(3, 4.50). The caller must use the function as part of an expression.

    Replacing RETURN with OUTPUT: displaying the answer does not supply the result required by the function’s caller.

    Missing result on a branch: trace every possible route and check that it returns a suitable value.

    Wrong result type: a fractional mean should return REAL, while a validity check should return BOOLEAN. The value returned must match the declared type.

    Returning too early: RETURN exits the function. Place it after any loop that must complete before the answer is ready.

    15 | DEFINE, TRACE AND TEST

    Decide what one result the caller needs. Choose the function’s name, parameter list and return type, then write its body so every possible route provides a result.

    For each test, record the argument values, parameter mapping, calculation or decisions inside the body, returned value and the caller’s final use of that value. Test boundaries such as score zero and one hundred, and zero iterations where a loop permits them.

    A useful explanation is: “TicketCost returns 13.5, which replaces the call in the expression. The caller then adds the delivery charge of two, resulting in Total equal to 15.5.”

    The next lesson explains local and global variables, including which parts of a program can use a declared variable.

    MATCH THE FUNCTION CODE TO ITS ROLE

    Terminology

    Terminology

    Function

    A named routine returning a single value to its calling expression.

    Definition

    Code specifying a function’s name, parameters if needed, result type and body.

    FUNCTION

    The keyword beginning a function definition.

    ENDFUNCTION

    The keyword closing a function definition.

    Body

    Instructions executed inside a routine when it is called.

    Parameter

    A named item in the definition receiving a supplied value.

    Argument

    A value or expression supplied at a call, also described as a parameter value.

    Caller

    The part of the program making a function call.

    Expression

    Values and operations evaluated to produce a result.

    Function call

    Use of a function within an expression to obtain its returned value.

    RETURNS

    The header keyword declaring the result’s data type.

    RETURN

    Supplies the result and ends the current function execution.

    Return type

    The data type of the value a function provides.

    Returned value

    The result replacing the call in the calling expression.

    BOOLEAN result

    A returned TRUE or FALSE value suitable for a condition.

    No-parameter function

    A function requiring no supplied arguments but still returning a value.

    Execution path

    A possible route through a routine’s instructions.

    Early return

    A RETURN reached before later instructions, which ends that function execution.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

    Select all correct choices. Each exact set earns one point.

    1. Which statements about a function definition are correct?
    2. Double returns twice its INTEGER parameter. Which uses are valid?
    3. Total ← Double(6) + 3. Which are correct?
    4. Which distinguish RETURNS and RETURN?
    5. Which scores make IsValidScore TRUE for inclusive limits 0 to 100?
    6. Which are correct for GradeLabel?
    7. What happens when RETURN is reached inside a function loop?
    8. Which statements about no-parameter functions and means are correct?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Define a function and explain how its result is used.

    2. Describe the roles of FUNCTION, RETURNS, RETURN and ENDFUNCTION.

    3. Trace Result ← Double(6).

    4. Explain why OUTPUT is not a substitute for RETURN.

    5. Calculate Total for TicketCost(3, 4.50) + 2.

    6. Explain why GradeLabel needs a result on every possible route.

    7. Explain why SumTo returns after NEXT rather than inside the loop.

    8. Suggest a return type for a mean, a validity check and a grade label, with reasons.

    BUILD IT | LARGER OF TWO NUMBERS

    Define Larger with INTEGER parameters First and Second, returning the larger value as INTEGER. Use selection and return a result on both routes. Store Larger(7, 4) in Best, then output Best. Test reversed arguments, equal arguments and two negative values. Predict the returned values before revealing the sample.

    Reveal one possible solution
    FUNCTION Larger(First : INTEGER, Second : INTEGER) RETURNS INTEGER
      IF First >= Second
        THEN
          RETURN First
        ELSE
          RETURN Second
      ENDIF
    ENDFUNCTION
    
    DECLARE Best : INTEGER
    Best ← Larger(7, 4)
    OUTPUT Best

    Larger(7, 4) returns seven; Larger(4, 7) also returns seven; Larger(5, 5) returns five; Larger(-3, -8) returns minus three. The equality case follows the TRUE branch but either equal value would be the correct result. Both paths return INTEGER, and the caller displays the returned value using a separate OUTPUT instruction.

    Flashcards

    Flashcards

    Click to flip. Select the ideas you need to revisit.

    0 cards selected for revision.

      Selections are kept while this page is open.

      Workbook

      Workbook

      COMING SOON

      The workbook for 8.1.6B.2 Define and Call Functions is coming soon. Complete the matching task and written questions in your exercise book.