Recap
- A procedure is a named group of instructions; it may have parameters and return a value. (Method and function are other names.)
- Parameter: input variable in the definition. Argument: value given in the call, matched by position.
- A call interrupts sequential flow. After the last statement or a
RETURN, control goes back to the point just after the call. RETURN(expression)sends the value back and ends the procedure at once.DISPLAY(expression)shows a value (and a space). It does not return anything.INPUT()returns a value typed by the user.- A call that returns a value can be assigned or used inside an expression.
Key relationships
| Idea | Notation | Example |
|---|---|---|
| Definition | PROCEDURE name(p1, p2) { ... } |
PROCEDURE rectArea(width, height) |
| Call as statement | name(a1, a2) |
greet("Mina") |
| Call as expression | result ← name(a1, a2) |
a ← rectArea(3, 4) |
| Return a value | RETURN(expression) |
RETURN(width * height) |
| Nested call | Inner call is evaluated first | DISPLAY(rectArea(rectArea(1, 2), 3)) |
Assumptions
- Arguments are evaluated before the procedure body runs.
- The number of arguments matches the number of parameters.
- A definition does nothing until the procedure is called.
Method for tracing a call
- Write the parameters, then the argument values beside them.
- Run the body line by line; note any
DISPLAYoutput in order. - Stop at the first
RETURNthat runs. - Replace the call by its returned value and continue evaluating.
Mistakes to avoid
- Swapping the order of arguments.
- Confusing
DISPLAYwithRETURN. - Running statements after a
RETURN. - Forgetting that
DISPLAYinside a procedure happens during the call. - Treating parameters as variables that existed before the call.
Worked mini-example
PROCEDURE f(n)
{
DISPLAY(n)
RETURN(n + 1)
}
DISPLAY(f(7))
Output: 7 8
The call f(7) runs first: it displays 7 and returns 8. Then the outer DISPLAY shows the returned 8. Output: 7 8.
Quick self-check
- In
PROCEDURE total(a, b)and the calltotal(2, 5), which are parameters and which are arguments? - What does a
RETURNstatement do besides giving a value back? - After
x ← f(7)finishes, where does the program continue?
Answers
aandbare parameters;2and5are arguments.- It ends the procedure immediately.
- At the statement immediately after the call.
Where marks are won and lost
Tracing questions give a procedure definition and a few calls and ask what is displayed or returned. Watch the order of arguments, early returns, and calls inside expressions. A second type asks which line of the program runs next after a call finishes. Others ask the difference between a parameter and an argument. Use the five-step checklist every time and track variables in a table. In the Create task, your own procedure must have at least one parameter that affects what it does, and you must show a call to it, so be ready to explain which argument went in and what came back.
Back to the full study guide for worked examples and explanations.