Skip to topic
    ← Back to course topics

    Returning a value/values from a subroutine — AQA A-Level Computer Science

    Returning a value from a subroutine transforms a procedure into a function, passing computed data back to the calling environment via the call stack or accumulator. In AQA A-Level Computer Science, students must master return statements, parameter passing mechanisms, and techniques for returning multiple values using composite data structures.

    Returning a value/values from a subroutine explained

    A function is a subroutine that sends a result back to the routine that called it.

    Read the full explanation

    The calling routine uses that result inside an expression, an assignment or as an argument to another subroutine. In Python a function returns with the return statement, for example def area(w, h): return w * h, and the caller writes total = area(3, 4), so total holds 12. A subroutine that returns a value must be used in a way that accepts that value, such as assigning it to a variable, printing it or passing it on. Being able to use such a subroutine means choosing the correct call, handling the returned value, and recognising when a function that returns several values must be unpacked into several variables. Practice with short traces of call-and-return sequences builds this skill reliably.

    Your focus

    1. Be able to use subroutines that return values to the calling routine.

    Which command word is this?

    Provide a detailed account of the mechanism or process, such as how a return address and return value are handled by the call stack.

    Returning a value/values from a subroutine exam tips

    Topic Overview

    Subroutines are self-contained modular blocks of code designed to perform specific tasks. When a subroutine computes information that must be reused by the wider program, it returns one or more values, distinguishing it as a function rather than a void procedure.

    Understanding return mechanisms is vital for program modularity, software reusability, and low-level architectural comprehension. This topic connects high-level procedural abstraction directly to stack frames, memory addresses, and parameter-passing conventions in the AQA syllabus.

    Key Concepts
    • →Functions versus Procedures: Functions evaluate to a value and must return data to the calling environment, whereas procedures perform actions without yielding a value.
    • →Call Stack Operation: Return values are placed into a CPU register (such as the accumulator) or a designated stack location while the return address redirects program flow back to the caller.
    • →Multiple Return Methods: Returning multiple data items requires packaging them into compound types (arrays, records, tuples, dictionary objects) or altering parameters passed by reference.
    • →Scope and Lifetime: Once a subroutine encounters a return statement, its execution ceases immediately and all local variables allocated in its stack frame are deallocated.
    Marking Points
    • Identifies the value a function returns and the statement that produces it
    • Assigns or uses the returned value in a later expression or output
    • Calls the subroutine with arguments in the correct order and number
    • Unpacks multiple returned values into matching variables
    Examiner Tips
    • 💡Trace the call step by step, noting the value returned at the return statement
    • 💡Check that the variable receiving the return value matches the type expected later
    • 💡When several values are returned, count them and match them to the same number of variables
    • 💡Always state the return type when defining functions in typed pseudocode or language-specific questions to secure data representation marks.
    • 💡Make sure your return statements in recursive routines return the recursive step itself (e.g., 'return n * factorial(n - 1)'), rather than simply calling the function without returning.
    Common Mistakes
    • Calls a function but discards its return value, so the result is never used; assign the result to a variable or use it in an expression
    • Treats a function call as if it changed a variable passed in, when the result must be captured from the return value; use the returned value instead
    • Passes arguments in the wrong order, producing a wrong result; match each argument to its parameter position
    • Misconception: 'Print' and 'Return' are interchangeable. Correction: 'Print' simply writes data to standard output (the screen) and leaves the calling code with no usable value; 'Return' passes data internally back to the program expression.
    • Misconception: Any code written below a return statement in the same block will still execute. Correction: A return statement immediately halts subroutine execution and pops the activation record, rendering unreachable subsequent code as dead code.
    • Misconception: Subroutines passed by value can modify the caller variable to simulate returning a value. Correction: Passing by value copies the argument, meaning changes made inside the subroutine do not persist outside unless explicitly returned.
    Revision Plan
    1. 1Day 1-3: Practice distinguishing functions from procedures by writing algorithms that assign returned values to variables across different contexts.
    2. 2Day 4-6: Implement subroutines that return compound data structures (tuples, lists, and records) and trace execution using stack frames.
    3. 3Day 7-10: Complete past AQA Paper 1 programming tasks focusing on recursive function unwinding and parameter passing by value vs reference.
    Exam Question Types
    • 📋Pseudocode Algorithm Writing: Writing or completing a function that processes an input and returns a calculated result or boolean flag.
    • 📋Trace Table and Stack Tracking: Tracing execution flow and identifying exact values returned to calling statements, particularly with nested or recursive calls.
    • 📋Conceptual Theory Questions: Comparing passing by value versus reference and explaining how return values interface with stack frames.
    Command Word Expectations (AQA)
    Describe

    Provide a detailed account of the mechanism or process, such as how a return address and return value are handled by the call stack.

    Write

    Produce syntactically valid code or clear standard AQA pseudocode showing explicit function headers, calculations, and matching return statements.

    Compare

    Identify both similarities and differences between methods of returning data (e.g. using return statements versus passing by reference).

    How Students Lose Marks (Examiner Pitfalls)
    Pitfall: Confusing printing an output with returning a value from a subroutine.
    ❌ Weak Answer (Loses Marks):The subroutine outputs the result by writing print(total) at the end of the code block.
    Example improved answer:The subroutine terminates execution and transfers data back to the calling instruction using the 'return total' statement, allowing the returned value to be assigned to a variable or evaluated within an expression.
    Examiner Tip: Always check the question phrasing: if an algorithm specifies a 'function' or asks to 'calculate and return', using 'print' or 'output' will immediately lose the return mark.
    Pitfall: Assuming a subroutine can only ever communicate a single atomic value back to the calling routine.
    ❌ Weak Answer (Loses Marks):A subroutine can only return one value because a return statement only takes one argument.
    Example improved answer:While a function traditionally returns a single data entity, multiple values can be returned by packaging them into composite data structures such as tuples, lists, or records, or by modifying variables passed by reference.
    Examiner Tip: In pseudocode and programming questions, clarify how multiple values are structured (e.g. returning a record or tuple containing quotient and remainder).
    Step-by-Step Worked Solutions

    Question: Write an algorithm in pseudocode for a function named 'CalculateStats' that takes an array of integers as a parameter and returns both the arithmetic mean and the range (maximum minus minimum) of the values.

    1. 1.Step 1: Define the function header with an identifier and array parameter, ensuring it specifies returning a composite structure: 'function CalculateStats(dataArray)'.
    2. 2.Step 2: Initialise accumulators and tracking variables: set 'total = 0', 'minVal = dataArray[0]', and 'maxVal = dataArray[0]'.
    3. 3.Step 3: Iterate through each element 'x' in 'dataArray', updating 'total = total + x', checking and updating 'minVal = min(minVal, x)', and 'maxVal = max(maxVal, x)'.
    4. 4.Step 4: Compute the mean by dividing 'total' by the length of 'dataArray', and calculate 'rangeVal = maxVal - minVal'.
    5. 5.Step 5: Bundle the results into a tuple or record structure and execute the return statement: 'return (mean, rangeVal)'.
    Final Answer: function CalculateStats(numbers) total = 0 minimum = numbers[0] maximum = numbers[0] for item in numbers total = total + item if item < minimum then minimum = item endif if item > maximum then maximum = item endif endfor mean = total / len(numbers) rangeVal = maximum - minimum return (mean, rangeVal) endfunction

    Question: Explain the role of the call stack when a recursive function returns a value back to its calling statement.

    1. 1.Step 1: Identify what is held on the call stack for each subroutine activation (stack frames containing return addresses, local variables, and parameters).
    2. 2.Step 2: Describe what occurs when the base case is reached and the return statement executes.
    3. 3.Step 3: Detail how the stack frame is popped from the top of the call stack, restoring the previous activation frame's execution context.
    4. 4.Step 4: Explain how the returned value is substituted into the pending expression at the retrieved return address until the original call completes.
    Final Answer: When a recursive function reaches a return statement, the top stack frame (containing local variables, parameters, and the return address) is popped off the call stack. The evaluated return value is transferred back to the memory location or CPU register indicated by the saved return address, resolving the suspended call and allowing unwinding to continue until the base frame terminates.
    Active Recall Memory Test
    What is the key functional difference between a procedure and a function?
    Key Fact: A function returns a value to the calling program environment, whereas a procedure executes statements without returning a value.
    Where is the return address stored when a subroutine is called during program execution?
    Key Fact: It is stored inside the subroutine's activation record (stack frame) on the call stack.
    Name two ways a subroutine can return multiple values to the calling routine.
    Key Fact: By returning a composite data structure (such as a tuple, record, or list) or by modifying variables passed by reference.
    What happens to the local variables of a subroutine when its return statement executes?
    Key Fact: Their memory space is deallocated as the subroutine stack frame is popped from the call stack.
    Frequently Asked Questions
    Can a function have more than one return statement in its code?
    Yes, a function can contain multiple return statements, typically placed within different conditional branches (such as 'if-else' structures). However, only one return statement will execute during any single subroutine call, as returning immediately terminates the subroutine. Good programming practice often advocates for a single entry and single exit point to maintain clarity.
    How do programming languages return multiple values if functions only return one thing?
    Languages achieve this by bundling multiple values into a single compound object. In Python, separating values with commas automatically constructs and returns a single 'tuple'. In languages like C# or Java, developers return a custom class instance, record, struct, or array containing the required fields.
    What is the difference between returning a value and passing a parameter by reference?
    Returning a value creates an explicit output that is passed back through the call stack into the expression that invoked the subroutine. Passing by reference provides the subroutine with the memory address of an existing variable, allowing the subroutine to mutate that variable directly in place without needing an explicit return statement.
    What happens if a function reaches the end of its code block without hitting a return statement?
    Depending on the programming language, the function will either return a default null value (such as 'None' in Python or 'undefined' in JavaScript) or cause a compilation/runtime error (such as in C++ or Java where a non-void function guarantees a typed return value).