Define and use a procedure
11.3 Structured Programming: Define and Use a Procedure 📚
What is a Procedure? 🤔
A procedure is like a recipe in a cookbook. It’s a named block of code that performs a specific task. Once you’ve written the recipe, you can use it any time you need that task done, without having to rewrite the steps.
Syntax of a Procedure 🛠️
In pseudocode, a procedure is defined with the keyword PROCEDURE followed by its name and optional parameters.
- PROCEDURE name(param1, param2, …)
- Procedure body (indented)
- END PROCEDURE
Example:
PROCEDURE greet(name)
PRINT "Hello, " + name + "!"
END PROCEDURE
Calling a Procedure 🚀
To use a procedure, simply write its name and supply any required arguments.
- greet("Alice")
- greet("Bob")
Parameters and Return Values 🔁
Parameters act like ingredients: they give the procedure the data it needs. A procedure can also return a value, similar to a finished dish.
- Input parameters – data passed into the procedure.
- Output parameters – data returned out of the procedure.
- Return type is optional in many languages; if omitted, the procedure returns void.
Example with return value:
PROCEDURE add(a, b)
RETURN a + b
END PROCEDURE
Scope and Local Variables 🌐
Variables declared inside a procedure are local – they exist only while the procedure runs. They cannot be accessed outside the procedure.
- DECLARE localVar
- Use localVar inside the procedure.
- After the procedure ends, localVar is destroyed.
Example: Calculating Factorial (Recursive) 🔢
Factorial of a number n is defined as:
$$ n! = n \times (n-1)! $$
Here’s a recursive procedure:
PROCEDURE factorial(n)
IF n = 0 THEN
RETURN 1
ELSE
RETURN n * factorial(n - 1)
END IF
END PROCEDURE
Exam Tips for Procedures 📌
- Always include the PROCEDURE keyword and the matching END PROCEDURE.
- Remember that parameters are passed by value unless specified otherwise.
- Check that the procedure’s return type matches the expected output.
- Use clear, descriptive names for procedures and parameters.
- When asked to write a procedure, start with the signature, then the body, and finish with the return statement.
Quick Quiz ❓
- What keyword marks the start of a procedure?
- Can a procedure access a variable declared outside its body?
- Write a simple procedure that prints “Goodbye!”.
Summary Table of Procedure Components 📊
| Component | Description | Example |
|---|---|---|
| Signature | Name + parameters | PROCEDURE greet(name) |
| Body | Code that performs the task | PRINT "Hello, " + name + "!" |
| Return | Optional value sent back to caller | RETURN a + b |
| End | Marks the end of the procedure | END PROCEDURE |
Revision
Log in to practice.