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.

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.

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