Structured programming

Computer Science AS · Programming. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science AS topics

The idea

A large program is split into modules. A procedure is a named block of statements that carries out one task and is run with CALL. A function also carries out a task but returns one value, so its call is written inside an expression and the returned value replaces the call. Use a module when the same task is needed in several places: the code is written once, tested once and reused.

Data goes into a module through parameters. Passed by value, the module gets a copy, so the caller's variable is not changed. Passed by reference, the module gets the address of the variable, so its changes do affect the caller's variable.

Efficient code avoids work that is not needed.

In simpler words

Big programs are split into small parts called modules. A procedure does a job. A function does a job and gives back one value. You write each part once and reuse it. Data goes in through parameters. By value sends a copy, so the original stays the same. By reference sends the real variable, so changes are kept.

An everyday comparison

Passing by value is like giving someone a photocopy of your notes: they can scribble on it and your copy stays clean. Passing by reference is like lending your original notebook: their changes are in your book. The comparison stops working because by reference passes the variable's address, so nothing is lent or returned; both names point to the same memory.

Rules to remember

Common mistake

Expecting a BYVAL parameter to change the variable in the calling program. Only a BYREF parameter can pass a changed value back.

In the exam

Write the header first with the parameter names, types and BYVAL or BYREF. For a function, include RETURNS and the type, and a RETURN statement. Explain the difference: a procedure is run with CALL; a function returns one value and is used in an expression. For parameters, state BYVAL passes a copy so the caller's variable is unchanged, and BYREF passes the address so changes affect the caller. Give one benefit of modules: written and tested once, then reused.

Worked example

What is output by this code?
PROCEDURE Adjust(BYVAL P : INTEGER, BYREF Q : INTEGER)
   P ← P * 2
   Q ← Q + P
ENDPROCEDURE

A ← 3
B ← 4
CALL Adjust(A, B)
OUTPUT A, " ", B

  1. P is a copy of A, so P starts at 3. Q refers to B, which holds 4.
  2. P ← 3 × 2 = 6. Only the copy changes, so A is still 3.
  3. Q ← 4 + 6 = 10. Q is passed by reference, so B becomes 10.

Answer: 3 10

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← ConstructsProgram development life cycle →Take a Computer Science AS test