# Functions & Return Values

- **Track:** Cambridge IGCSE™ Computer Science (0478 / 0984) (CAMBRIDGE IGCSE 0478)
- **Module:** Section 8: Programming Concepts & File Handling
- **Estimated Duration:** 15 minutes
- **Access:** Open Theory (All-Access for Interactive IDE &amp; Autotests)

---

## Theory & Conceptual Background

In structured programming, complex programs are broken down into manageable subroutines. While **procedures** perform tasks without sending back a value, **functions** are specialized subroutines designed specifically to compute and return a single result.

---

## 1. What is a Function?

A **function** is a self-contained block of code that:

1. Accepts zero or more input **parameters**.
2. Performs a calculation or data manipulation.
3. **Returns exactly one value** of a declared data type back to the calling statement.

Because a function yields a value, it is invoked wherever an expression is valid—such as the right-hand side of an assignment statement, inside an `OUTPUT` statement, or within a condition.

---

## 2. Functions vs. Procedures: Key Differences

Understanding the distinction between functions and procedures is a frequent exam requirement:

  
| Feature | Procedure | Function |
| --- | --- | --- |
| **Return Value** | Does **not** return a value. | Returns **exactly one** value. |
| **Header Keyword** | `PROCEDURE Name(...)` | `FUNCTION Name(...) RETURNS DataType` |
| **Termination Keyword** | `ENDPROCEDURE` | `ENDFUNCTION` |
| **Return Mechanism** | None (or updates `BYREF` parameters). | `RETURN Expression` |
| **How it is Called** | Standalone statement with `CALL`: <br>`CALL PrintHeader()` | Part of an expression or assignment: <br>`Total <- CalcTax(Subtotal)` <br>`OUTPUT CalcTax(Subtotal)` |
| **Can use `CALL`?** | **Yes** (mandatory in Cambridge pseudocode). | **No** (syntax error). |

---

## 3. Function Declaration Syntax

The standard Cambridge pseudocode template for defining a function is:

```pseudocode
FUNCTION FunctionIdentifier(Parameter1 : DataType, Parameter2 : DataType) RETURNS ReturnDataType
    // Local declarations and computation
    RETURN CalculatedValue
ENDFUNCTION
```

### Key Elements:

- `FUNCTION`: The opening keyword declaring the subroutine.
- `RETURNS ReturnDataType`: Declares the data type of the value that the function will yield (e.g., `RETURNS REAL`, `RETURNS BOOLEAN`).
- `RETURN Value`: Halts function execution and transmits the value back to the caller.
- `ENDFUNCTION`: Closes the subroutine definition.

---

## 4. Worked Example: Currency Conversion Function

Suppose an e-commerce platform needs a function that converts an amount in US Dollars to British Pounds given an exchange rate:

```pseudocode
FUNCTION ConvertUSDToGBP(AmountUSD : REAL, Rate : REAL) RETURNS REAL
    DECLARE ConvertedAmount : REAL
    ConvertedAmount <- AmountUSD * Rate
    RETURN ConvertedAmount
ENDFUNCTION

// Calling the function:
DECLARE PriceInUSD : REAL
DECLARE PriceInGBP : REAL

PriceInUSD <- 49.99
PriceInGBP <- ConvertUSDToGBP(PriceInUSD, 0.79)

OUTPUT "Price in GBP: £", PriceInGBP
```

### Trace of Execution:

1. The main program assigns `49.99` to `PriceInUSD`.
2. The assignment `PriceInGBP <- ConvertUSDToGBP(PriceInUSD, 0.79)` calls `ConvertUSDToGBP`.
3. Parameter `AmountUSD` receives `49.99`, and `Rate` receives `0.79`.
4. `ConvertedAmount` is calculated as `49.99 * 0.79 = 39.4921`.
5. `RETURN ConvertedAmount` passes `39.4921` back to the caller.
6. The calling assignment receives `39.4921` and stores it into `PriceInGBP`.

---

## 5. Parameter Passing: By Value vs By Reference

- **By Value (`BYVAL`)**: The default passing mechanism for functions. A copy of the caller's value is passed into the subroutine. Any modifications to the parameter inside the function do **not** affect the caller's variable. Functions should avoid altering parameter variables to maintain predictability (no side effects).
- **By Reference (`BYREF`)**: Passes a pointer to the original variable in memory. While valid in procedures, functions should strictly use `RETURN` to pass information out.

---

## 6. Common Pseudocode Pitfalls

1. **Calling a function with `CALL`**:

```pseudocode
// INCORRECT
   CALL CalculateArea(10, 5)

   // CORRECT
   Area <- CalculateArea(10, 5)
```

1. **Missing `RETURNS DataType`**: Omitting the return type in the function header is a syntax violation.
2. **Missing `RETURN`**: Failing to provide a `RETURN` statement leaves the calling expression undefined.
3. **Returning multiple values**: In Cambridge pseudocode, a function cannot return a tuple or list of values; it must return exactly one value.

---

## Interactive Exercises & Autotest Specifications

### Exercise 1: Exam-Style Check: Core Characteristics of Functions vs Procedures (Multiple choice, 30 XP)

**Instructions:**
Which statement correctly describes a key difference between a function and a procedure in Cambridge pseudocode?

**Options:**
- **A**: A procedure returns multiple values to the calling routine, whereas a function returns no value.
- **B**: A function must be invoked using the CALL keyword, whereas a procedure is assigned to a variable.
- **C**: A function cannot accept parameters, whereas a procedure can accept parameters.
- **D**: A function returns a single value to the calling expression, whereas a procedure executes actions without returning a value.


**Autotest Expectations:**
- **Correct difference between function and procedure identified**: `selection_match` -> Expected: `opt_func_return`

### Exercise 2: Exam-Style Question: Complete Function Header and Return (Fill in blank, 35 XP)

**Instructions:**
Complete the function definition for `CalcBonus` which accepts `Salary : REAL` and `Rating : INTEGER`, and returns `REAL`:

```pseudocode
FUNCTION CalcBonus(Salary : REAL, Rating : INTEGER) [blank_1] REAL
    IF Rating = 5 THEN
        [blank_2] Salary * 0.10
    ELSE
        [blank_3] Salary * 0.05
    ENDIF
[blank_4]
```


**Starter Code:**
```text
{"template":"1. [blank_1]\n2. [blank_2]\n3. [blank_3]\n4. [blank_4]","word_bank":["RETURNS","RETURN","ENDFUNCTION","FUNCTION","PROCEDURE","CALL"],"prompt":"Exam-Style Question: Complete Function Header and Return","blanks":[{"id":"blank_1"},{"id":"blank_2"},{"id":"blank_3"},{"id":"blank_4"}]}
```

**Autotest Expectations:**
- **Return type keyword RETURNS**: `text_exact` -> Expected: `RETURNS`
- **Return value keyword RETURN**: `text_exact` -> Expected: `RETURN`
- **Return value keyword RETURN**: `text_exact` -> Expected: `RETURN`
- **Function closing keyword ENDFUNCTION**: `text_exact` -> Expected: `ENDFUNCTION`

### Exercise 3: Independent Practice: Return a maximum (Pseudocode, 30 XP)

**Instructions:**
Write a function returning the larger of two integers. Read two integers, call your function and output its returned value.

Write a complete program. Read inputs in the stated order. Output only the requested results, one per line, without input prompts. Test with your own values before submitting.


**Starter Code:**
```text
// Plan your solution, then write your program.

```

**Autotest Expectations:**
- **First larger**: `test_case` -> Expected: `{&quot;inputs&quot;:[9,2],&quot;output&quot;:&quot;9&quot;}`
- **Second larger**: `test_case` -> Expected: `{&quot;inputs&quot;:[2,9],&quot;output&quot;:&quot;9&quot;}`
- **Negative values**: `test_case` -> Expected: `{&quot;inputs&quot;:[-8,-3],&quot;output&quot;:&quot;-3&quot;}`
- **Equal**: `test_case` -> Expected: `{&quot;inputs&quot;:[4,4],&quot;output&quot;:&quot;4&quot;}`

