11.3 Structured Programming

Bulk view disabled for Guests. View lessons individually.

Procedures and Functions

1. Procedures vs. Functions

A subroutine is a self-contained block of code that performs a specific task. Using them makes code reusable and easier to debug.

Procedures

Performs a task but does not return a value to the main program. It is "called" as a standalone statement.

PROCEDURE DisplayHeader()
  OUTPUT "--- System ---"
ENDPROCEDURE

// To use it:
CALL DisplayHeader()

Functions

Performs a calculation and returns a single value. It must be used as part of an expression or assignment.

FUNCTION Add(x, y) RETURNS INT
  RETURN x + y
ENDFUNCTION

// To use it:
Result ← Add(5, 10)

2. Parameter Passing

How data is "handed over" to a subroutine determines whether the original variable can be modified.

Method Description Original Variable?
BYVAL (Value) A local copy of the data is made. The subroutine works on the copy. No change
BYREF (Reference) The subroutine is given the memory address of the original variable. Changed!

ByRef Example (The Swap Pattern)

PROCEDURE Swap(BYREF a : INT, BYREF b : INT)
  DECLARE Temp : INT
  Temp ← a
  a ← b
  b ← Temp
ENDPROCEDURE

// If Num1=10 and Num2=20, calling Swap(Num1, Num2)
// will physically swap the values in Num1 and Num2.

3. Variable Scope

  • Local Variables: Declared inside a subroutine. They only exist while the subroutine is running and cannot be accessed from outside.
  • Global Variables: Declared in the main program. They can be accessed from anywhere, but overusing them is considered poor programming practice (it makes debugging harder).
⚠️ Exam Note: Arrays as Parameters

In most 9618 exam questions, arrays are passed BYREF by default. This is because copying a massive array (BYVAL) consumes too much memory and slows down the processor.