Sub topic 5
Procedures, Parameters, and Return Values
This chapter assumes you have written functions with parameters in at least one programming language. It also assumes you know the conventions from earlier chapters: ← for assignment, keyword pairs such as IF ... END IF, indentation for structure, and 1-based arrays by default. The chapter covers how to package steps into named units in pseudocode, how data goes into and comes out of those units, and the mistakes that make such pseudocode ambiguous.
Why Name a Block of Steps
Once an algorithm grows past about a dozen lines, a reader can no longer keep all of it in their head. A named unit lets the reader treat a group of steps as one action, such as "find the largest value" or "swap two elements," without reading its insides every time. In pseudocode this matters more than in real code. A compiler or test suite won't check pseudocode for you, so the reader's attention is the only safeguard you have.
Named units also make tracing practical. If Sum has already been checked on its own, a trace of a larger algorithm that calls it can treat each call as one step that produces a known value.
FUNCTION Versus PROCEDURE
Many pseudocode styles separate units that compute a value from units that perform an action. This tutorial uses that separation.
| Keyword | Produces a value? | Typical use | How it is called |
|---|---|---|---|
| `FUNCTION` | Yes, through `RETURN expr` | Computing a result: maximum, sum, index | Inside an expression: `m ← FindMax(A, n)` |
| `PROCEDURE` | No | Changing state: sorting in place, printing | As a statement: `CALL Swap(A, 1, 3)` or just `Swap(A, 1, 3)` |
A FUNCTION must return a value on every path through its body. A PROCEDURE may use a bare RETURN to stop early, but it never returns a value.
FUNCTION Sum(A, n)
total ← 0
FOR i ← 1 TO n DO
total ← total + A[i]
END FOR
RETURN total
END FUNCTION
FUNCTION Average(A, n)
RETURN Sum(A, n) / n
END FUNCTION
PROCEDURE Swap(A, i, j)
temp ← A[i]
A[i] ← A[j]
A[j] ← temp
END PROCEDUREAverage shows the payoff of naming. Its body is one line because Sum takes care of the loop.
Parameters and Arguments
A parameter is the name in the header, such as A and n in Sum(A, n). An argument is the value supplied at the call, such as scores and 5 in Sum(scores, 5). When the call happens, each parameter is bound to its argument by position: the first argument goes to the first parameter, the second to the second, and so on.
Pseudocode has no type checker, so put the meaning of each parameter where the reader will see it. A short comment line after the header usually does the job:
FUNCTION IndexOf(A, n, target)
// A: array of n values, 1-based; target: value to look for
// Returns the first index i with A[i] = target, or 0 if none
FOR i ← 1 TO n DO
IF A[i] = target THEN
RETURN i
END IF
END FOR
RETURN 0
END FUNCTIONThe array length n is passed as its own parameter. Real languages often store the length inside the array, but pseudocode should not assume they do. An explicit n also makes the loop bounds easy to see during a trace.
Return Values and Early Exit
RETURN does two things at once. It ends the unit immediately, and in a FUNCTION it hands a value back to the caller. In IndexOf, the RETURN i inside the loop skips every remaining iteration. A reader tracing the loop has to stop the trace at that point and not keep counting i upward.
Pay attention to the final RETURN 0. If you leave it out, the function has a path, the target-not-found case, that falls off the end with no value. A real compiler might reject that or return something undefined. In pseudocode, nobody notices until someone translates it. Check every function for a return on every path.
The not-found value was chosen deliberately. With 1-based arrays, 0 is never a valid index, so it works as a "not found" signal. If you move to a 0-based language, 0 becomes a real index, and the signal has to change to something like -1. A later chapter covers that translation step.
Local Variables and Scope
Variables created inside a unit, such as total in Sum or temp in Swap, are local. They exist only while that call is running, and they are separate from any variable with the same name in the caller. Parameters are local too. Assigning a new value to n inside Sum would not change the caller's n.
This rule is what lets you trace a called unit in its own small trace table and then carry only its return value back into the caller's table. Avoid global variables in pseudocode. If a unit needs a value, pass it in. If the caller needs a result, return it.
How Arguments Are Passed
Swapping two plain variables runs into the question of how arguments are passed:
PROCEDURE SwapValues(x, y)
temp ← x
x ← y
y ← temp
END PROCEDUREIf scalars are passed by value, x and y are copies, so SwapValues(a, b) changes nothing in the caller. If they are passed by reference, x and y are other names for a and b, so the swap works. Pseudocode has no fixed rule for this, so you must state one. This tutorial uses the common textbook convention:
- Scalars (numbers, booleans, single characters) are passed by value.
- Arrays are passed by reference. Changing
A[i]inside a unit changes the caller's array.
That convention is why Swap(A, i, j) works and SwapValues(x, y) does not. If a unit needs to change a caller's scalar, return the new value and let the caller assign it, or mark the parameter explicitly with something like OUT x and explain that marker once at the top of your document.
Seeing the Convention in Real Code
Python's behavior is close to this convention, which makes it a useful check. Rebinding a parameter name does not affect the caller, while changing a list's contents does.
def increment(x):
x = x + 1 # rebinds the local name only
return x
def swap(a, i, j):
a[i], a[j] = a[j], a[i] # mutates the caller's list
n = 5
increment(n)
print(n) # 5: the caller's n is unchanged
n = increment(n)
print(n) # 6: the caller assigns the returned value
values = [3, 7, 2]
swap(values, 0, 2) # 0-based indices in Python
print(values) # [2, 7, 3]Strictly speaking, Python passes references to objects in every case. Its integers can't be changed in place, so for them the result looks like pass by value. Other languages behave differently. C++ has & reference parameters, for example. That variation is why the convention belongs in the pseudocode itself and should not be left for the reader to guess.
Writing a Contract
A clear unit states a precondition, which must be true when the unit is called, and a postcondition, which the unit guarantees when it finishes. For Average, the precondition is n ≥ 1. Without it, the division by n is undefined. For Swap, the precondition is 1 ≤ i, j ≤ n, and the postcondition is that the values at positions i and j have traded places and nothing else has changed.
Contracts tell a tracer which inputs are legal and which results to expect. They also point straight at edge cases. Average with n = 0 breaks its precondition, so either the caller must never do that or the function must handle it explicitly.
Common Errors
- Missing return path: a
FUNCTIONwhoseIFbranch returns while theELSEpath falls through with no value. - Ignored return value: writing
Sum(A, n)as a bare statement and then usingtotalin the caller, as if the local variable were visible there. - Unstated passing rule: writing a procedure that changes a scalar parameter and expecting the caller to see the change.
- Argument order mix-ups: calling
IndexOf(target, A, n)when the header isIndexOf(A, n, target). Binding is positional, so the names at the call site do not help. - Hidden globals: reading a variable inside a unit that was never passed in, so the unit can't be traced on its own.
- Mixed roles: a
FUNCTIONthat both returns a value and quietly reorders its array argument. If both effects are needed, document both in the contract.
Exercise
Under this tutorial's convention, what does the caller's array contain after B ← [4, 1, 8], x ← 2, then Mystery(B, x), where PROCEDURE Mystery(A, k) runs A[k] ← A[k] × 10 and then k ← k + 1? What is the caller's x afterward?
Show answer
B is [4, 10, 8], because arrays are passed by reference, so writing A[2] changes B[2]. x is still 2, because k is a local copy of the scalar argument and incrementing it does not affect the caller.
Exercise
This function is meant to return the larger of two numbers. Find the defect and fix it: FUNCTION Larger(a, b) / IF a > b THEN RETURN a END IF / IF b > a THEN RETURN b END IF / END FUNCTION.
Show answer
When a = b, neither condition is true and the function reaches END FUNCTION without returning a value. Fix it by replacing the second IF with an unconditional RETURN b after the first IF, so every path returns a value.
Exercise
Write a FUNCTION CountGreater(A, n, t) that returns how many elements of the 1-based array A are greater than t. State its precondition and say what it should return when n = 0.
Show answer
FUNCTION CountGreater(A, n, t): count ← 0; FOR i ← 1 TO n DO IF A[i] > t THEN count ← count + 1 END IF END FOR; RETURN count; END FUNCTION. The precondition is n ≥ 0 with A holding at least n elements. When n = 0, the loop body never runs and the function returns 0, which is correct.