📑 Contents

Chapter 11.3: Structured Programming

9618 AS Computer Science

📚 Learning Objectives
🌟 Did You Know?

When writing programs, we should avoid long, repetitive code. Procedures and functions help to keep our programs simple and short. They are fundamental building blocks in structured programming that enable decomposition - breaking down complex problems into smaller, manageable sub-tasks!

📋 Prior Knowledge Required
Complex Problem Module 1 Module 2 Module 3 Procedure Function Procedure Decomposition → Modules → Subroutines

1. What are Functions and Procedures For?

Decomposition is a problem-solving technique that involves breaking down a complex problem into smaller, more manageable sub-tasks. Each sub-task can be considered as a 'module' or Subroutine.

📖 Definition: Modules

Modules are of two types: Functions and Procedures.

User-defined subroutines are written by programmers and used only in that specific program in which they are written.

1.1 Why Use Subroutines?

✅ Advantages of Using Subroutines
💡 Real-Life Analogy

A real-life example of a procedure is brushing your teeth. There are several steps involved: getting your toothbrush, squeezing toothpaste onto the brush, brushing all teeth, rinsing your mouth, and putting everything away. Each time you brush your teeth, you follow this same procedure - just like calling a subroutine in a program!

⚠️ Key Distinction

Both functions and procedures are small sections of code that can be repeated through a program. The difference between them is:

PROCEDURE Main Program CALL Procedure performs task ✗ No return value FUNCTION Main Program CALL Function calculates RETURN value ✓ Returns a value

2. Procedures

A procedure groups together a number of steps and gives them a name known as an identifier. We can use this identifier when we want to refer to this group of steps.

📖 Key Characteristics of Procedures

2.1 Procedure Syntax in Pseudocode

📝 Procedure Definition Format
PROCEDURE <ProcedureIdentifier>(<parameterList>) <statement(s)> ENDPROCEDURE
💡 Calling a Procedure

To call a procedure in pseudocode:

CALL <procedureIdentifier>() CALL <procedureIdentifier>(Value1, Value2, ...)

When parameters are used, values must be of the correct data type and in the same sequence.

2.2 Procedure Example: Without Parameters

PROCEDURE Message() OUTPUT "CS Made Easy" ENDPROCEDURE // To call this procedure: CALL Message()

2.3 Procedure Example: With Parameters

PROCEDURE total(Num1 : INTEGER, Num2 : INTEGER) Total ← Num1 + Num2 OUTPUT "Sum of Numbers = ", Total ENDPROCEDURE // To call this procedure: CALL total(9, 5)

2.4 Procedure Example: Input Validation

PROCEDURE InputOddNum() REPEAT INPUT "Enter an odd number: " Num UNTIL Num MOD 2 = 1 OUTPUT "Valid number entered" ENDPROCEDURE // To call this procedure: CALL InputOddNum()

3. Procedures in Python

Consider this excerpt from a Python game program which prints player information on the screen:

print("Your score: " + str(score)) time.sleep(1) print("High score: " + str(high_score)) time.sleep(1) print("Lives remaining: " + str(lives)) time.sleep(1)
⚠️ The Problem

Suppose you wanted to print out the player information at these different points in the game:

You would need to repeat those six lines of code on each occasion, giving a total of 24 lines of code simply to display the player information!

3.1 Creating a Procedure in Python

To create a procedure, first give the procedure a name. A good name for the player information procedure could be update_display. Use the def statement to name a procedure:

def update_display(): print("Your score: " + str(score)) time.sleep(1) print("High score: " + str(high_score)) time.sleep(1) print("Lives remaining: " + str(lives)) time.sleep(1)

3.2 Calling a Procedure in Python

Once a procedure is named and written, it can be called at any point in the program. Simply use its name (include the brackets):

# End of level update_display() # Lose a life update_display() # Beat high score update_display() # Game over update_display()
🌟 Code Reduction

Using this procedure greatly reduces the amount of code that has to be included in the program. Instead of 24 lines, you now have just 6 lines in the procedure + 4 calls = 10 lines total!

Main Program End of level → CALL update_display() Lose a life → CALL update_display() PROCEDURE update_display() • Print score • Print high score • Print lives • Wait between prints No value returned

4. Functions

A function groups together a number of steps and gives them a name known as an identifier. Functions operate in a similar way to procedures, except that in addition they return a single value to the point at which they were called.

📖 Key Characteristics of Functions

4.1 Function Syntax in Pseudocode

📝 Function Definition Format
FUNCTION <functionIdentifier>(<parameterList>) RETURNS <dataType> <statement(s)> RETURN <value> ENDFUNCTION

4.2 Function Example: Odd Number Input

FUNCTION InputOddNumber() RETURNS INTEGER REPEAT INPUT "Enter an odd number: " Num UNTIL Num MOD 2 = 1 OUTPUT "Valid number entered" RETURN Num ENDFUNCTION // To call this function: X ← InputOddNumber()

4.3 Function Example: Maximum of Two Numbers

FUNCTION Max(Number1: INTEGER, Number2: INTEGER) RETURNS INTEGER IF Number1 > Number2 THEN RETURN Number1 ELSE RETURN Number2 ENDIF ENDFUNCTION // Using (calling) the function: OUTPUT "Max Number is = ", Max(10, 2)
💡 Important Note

When a subroutine is called, we supply arguments in brackets. Arguments supplied are assigned to the corresponding parameter of the subroutine.

The order of parameters in the parameter list must be the same as the order in the list of arguments. This is known as the subroutine interface.

4.4 Python Function Example: Dice Roll

Look at this excerpt from a Python role-playing game program which simulates the throwing of a dice:

import random def roll_dice(sides): number = random.randint(1, sides) return number sides = int(input("How many sides does the dice have?")) throw = roll_dice(sides) print(throw)

5. Procedures vs Functions Comparison

Feature Procedure Function
Returns a value? NO YES
Called using CALL statement Part of an expression
Primary purpose Perform a task Calculate and return a value
Use when you need To execute actions without returning data A result or calculated value
Example use case Display menu, print report, update display Calculate sum, find maximum, validate input
Can use BYREF? Yes No (should not)
PROCEDURE PROCEDURE Greet(Name) OUTPUT "Hello, " + Name CALL Greet("Alice") Output: Hello, Alice ✗ No return value FUNCTION FUNCTION Add(A, B) RETURN A + B Result ← Add(5, 3) Result = 8 ✓ Returns value 8
🧠 Memory Trick

Procedure = Performs a task (like a recipe - just does something)

Function = Finds an answer (like a calculator - gives you a result)

6. Parameter Passing

Parameter passing is the method by which values or references are given to procedures or functions so they can use or modify data during execution.

📖 Key Terminology

6.1 BYVAL (By Value)

📝 Passing Parameters By Value

6.2 BYREF (By Reference)

📝 Passing Parameters By Reference
Keyword What It Does
BYVAL Passes a copy of the value (no change to original)
BYREF Passes a reference to the variable (can be modified)
⚠️ Important Rules

7. BYVAL vs BYREF Examples

7.1 BYVAL Example

PROCEDURE OutputSymbols(BYVALUE NumberOfSymbols : INTEGER, Symbol : CHAR) DECLARE Count : INTEGER FOR Count ← 1 TO NumberOfSymbols OUTPUT Symbol // without moving to next line NEXT Count ENDPROCEDURE // To call this procedure: CALL OutputSymbols(6, '*')

Output: ******

7.2 BYREF Example: Swapping Values

PROCEDURE Swap(BYREF X : INTEGER, BYREF Y : INTEGER) DECLARE Temp : INTEGER Temp ← X X ← Y Y ← Temp ENDPROCEDURE // Main program A ← 5 B ← 10 CALL Swap(A, B) OUTPUT A, B // Output: 10, 5
💡 What Happens?

When Swap is called with BYREF:

BYVAL (By Value) Variable A Value: 5 copy Param X Value: 5 X changes to 10 inside procedure Variable A Value: 5 ✓ Original UNCHANGED! BYREF (By Reference) Variable A Value: 5 pointer Param X Value: 5 Same memory location! X changes to 10 Variable A Value: 10 ✗ Original CHANGED!

8. Worked Example

Question: A video-conferencing program supports up to six users. Speech from each user is sampled and digitised. Digitised values are stored in array Sample.

The array Sample consists of 6 rows by 128 columns and is of type integer. Each row contains 128 digitised sound samples from one user.

The digitised sound samples from each user are to be processed to produce a single value which will be stored in a 1D array Result of type integer. This process will be implemented by procedure Mix().

A procedure Mix() will:

Write pseudocode for procedure Mix(). Assume Sample and Result are global. [6 marks]

8.1 Solution

PROCEDURE Mix() DECLARE Count, Total, ThisNum : INTEGER DECLARE ThisUser, ThisSample : INTEGER FOR ThisSample ← 1 TO 128 Count ← 0 Total ← 0 FOR ThisUser ← 1 TO 6 IF Sample[ThisUser, ThisSample] > 10 THEN Count ← Count + 1 Total ← Total + Sample[ThisUser, ThisSample] ENDIF NEXT ThisUser Result[ThisSample] ← INT(Total / Count) NEXT ThisSample ENDPROCEDURE
📝 Mark Scheme Breakdown

9. Exam-Style Questions

1. Explain the difference between a procedure and a function. [4 marks]

Answer:

  • A procedure does not return a value to the calling program
  • A function returns a single value to the point where it was called
  • Procedures are called using the CALL statement
  • Functions are called as part of an expression (not using CALL)
  • Additional point: Functions must include a RETURN statement; procedures do not
  • Additional point: Functions should not use BYREF parameters; procedures can
2. Write a procedure called DisplayStars that takes one integer parameter and outputs that number of asterisks (*) on the same line. [4 marks]

Answer:

PROCEDURE DisplayStars(NumberOfStars : INTEGER) DECLARE Count : INTEGER FOR Count ← 1 TO NumberOfStars OUTPUT "*" // without moving to next line NEXT Count ENDPROCEDURE

Additional points for deeper understanding:

  • The procedure uses a loop to iterate the correct number of times
  • OUTPUT without newline keeps stars on same line
3. Write a function called CalculateArea that takes two integer parameters (length and width) and returns the area as an integer. [4 marks]

Answer:

FUNCTION CalculateArea(Length : INTEGER, Width : INTEGER) RETURNS INTEGER DECLARE Area : INTEGER Area ← Length * Width RETURN Area ENDFUNCTION

Additional points:

  • Function header includes RETURNS keyword with data type
  • RETURN statement is mandatory in functions
  • Can be called as: Result ← CalculateArea(5, 3)

9. Exam-Style Questions (Continued)

4. Explain the difference between passing a parameter by value (BYVAL) and by reference (BYREF). [4 marks]

Answer:

  • BYVAL passes a copy of the value to the subroutine
  • Changes made to the parameter do not affect the original variable
  • BYREF passes a pointer to the memory location of the variable
  • Changes made to the parameter do affect the original variable
  • Additional: BYREF requires the argument to be a variable (not a literal value)
  • Additional: BYVAL is the default if no keyword is specified
5. Write a function MakeString() that takes two parameters: a count (integer) and a character. It should generate and return a string of length equal to count, made up of the character. Return "ERROR" if count is less than 1. [5 marks]

Answer:

FUNCTION MakeString(Count : INTEGER, Char : CHAR) RETURNS STRING DECLARE Result : STRING DECLARE i : INTEGER Result ← "" IF Count < 1 THEN RETURN "ERROR" ENDIF FOR i ← 1 TO Count Result ← Result + Char NEXT i RETURN Result ENDFUNCTION

Example: MakeString(3, 'Z') returns "ZZZ"

6. A procedure CountVowels() takes a string parameter and counts the occurrences of each vowel (a, e, i, o, u). Counts are stored in a global 1D array CharCount[6] of type INTEGER. Write pseudocode for this procedure. [6 marks]

Answer:

PROCEDURE CountVowels(Text : STRING) DECLARE i : INTEGER DECLARE Char : CHAR // Initialize array FOR i ← 1 TO 6 CharCount[i] ← 0 NEXT i FOR i ← 1 TO LENGTH(Text) Char ← UCASE(Text[i]) IF Char = 'A' THEN CharCount[1] ← CharCount[1] + 1 ELSE IF Char = 'E' THEN CharCount[2] ← CharCount[2] + 1 ELSE IF Char = 'I' THEN CharCount[3] ← CharCount[3] + 1 ELSE IF Char = 'O' THEN CharCount[4] ← CharCount[4] + 1 ELSE IF Char = 'U' THEN CharCount[5] ← CharCount[5] + 1 ELSE IF Char >= 'A' AND Char <= 'Z' THEN CharCount[6] ← CharCount[6] + 1 // Other letters ENDIF NEXT i ENDPROCEDURE

9. Exam-Style Questions (Continued)

7. Describe three advantages of using subroutines in a program. [3 marks]

Answer (any three):

  • Reusability: Code can be called from multiple places
  • Maintainability: Changes only need to be made once
  • Testing: Subroutines can be tested independently
  • Readability: Code is easier to understand
  • Collaboration: Different programmers can work on different subroutines
  • Reduced errors: Less code duplication means fewer chances for mistakes
8. Write a procedure Swap() that exchanges the values of two integer variables passed by reference. [4 marks]

Answer:

PROCEDURE Swap(BYREF X : INTEGER, BYREF Y : INTEGER) DECLARE Temp : INTEGER Temp ← X X ← Y Y ← Temp ENDPROCEDURE

Key points:

  • BYREF is essential - otherwise original values wouldn't change
  • Temporary variable is needed to hold one value during swap
  • Without Temp, one value would be lost
9. Write a function Max() that takes two integer parameters and returns the larger value. [4 marks]

Answer:

FUNCTION Max(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER IF Number1 > Number2 THEN RETURN Number1 ELSE RETURN Number2 ENDIF ENDFUNCTION

Usage: OUTPUT "Max is: ", Max(10, 25) // Outputs: Max is: 25

10. Explain why functions should not use BYREF parameters. [3 marks]

Answer:

  • Functions are designed to return a single value through the RETURN statement
  • Using BYREF creates a "side effect" - modifying variables outside the function
  • This makes code harder to debug and understand
  • It violates the principle that functions should be pure (no side effects)
  • If you need to modify multiple values, use a procedure with BYREF instead

10. Glossary

Subroutine
A named block of code that performs a specific task and can be called from anywhere in the program. Includes both procedures and functions.
Procedure
A subroutine that performs a specific task but does NOT return a value to the calling program. Called using the CALL statement.
Function
A subroutine that performs a calculation or task and RETURNS a single value to the calling program. Called as part of an expression.
Parameter
A variable in a subroutine definition that accepts a value passed in from the calling program.
Argument
The actual value or variable passed to a subroutine when it is called.
BYVAL (By Value)
A method of passing parameters where a copy of the value is passed. Changes to the parameter do not affect the original variable.
BYREF (By Reference)
A method of passing parameters where a pointer to the variable's memory location is passed. Changes to the parameter DO affect the original variable.
Header
The first line of a subroutine definition that includes the name, parameter list, and (for functions) return type.
Decomposition
Breaking down a complex problem into smaller, more manageable sub-tasks (modules).
Identifier
The name given to a subroutine, variable, or other programming element.
RETURN Statement
A statement in a function that sends a value back to the calling program and exits the function.
Module
A self-contained section of code that performs a specific task. Also called a subroutine.

11. Exam Success Tips (Part 1)

💡 Procedure vs Function - Quick Check
💡 BYVAL vs BYREF - Remember This!
🧠 Memory Trick: The Parameter Rules
❌ Common Mistakes to Avoid
⚠️ Exam Writing Tips

11. Exam Success Tips (Part 2)

💡 Writing Subroutines - Step by Step
  1. Write the keyword: PROCEDURE or FUNCTION
  2. Give it a meaningful name (identifier)
  3. Add parameters in brackets with data types
  4. For functions, add RETURNS and the data type
  5. Write the body (indented)
  6. For functions, include RETURN statement
  7. End with ENDPROCEDURE or ENDFUNCTION
📝 Template for Procedures
PROCEDURE Name(Param1 : TYPE, Param2 : TYPE) // Declare local variables // Write statements ENDPROCEDURE // Calling: CALL Name(value1, value2)
📝 Template for Functions
FUNCTION Name(Param1 : TYPE, Param2 : TYPE) RETURNS TYPE // Declare local variables // Write statements RETURN value ENDFUNCTION // Calling: Result ← Name(value1, value2) OUTPUT Name(value1, value2)
🌟 Pro Tips for Higher Marks
💡 Answer Strategy

12. Key Takeaways

📌 Summary Points

Subroutines

Procedures

Functions

Parameter Passing

SUBROUTINES PROCEDURE ✗ No return value ✓ Uses CALL ✓ Can use BYREF FUNCTION ✓ Returns value ✗ No CALL keyword ✗ No BYREF PARAMETER PASSING BYVAL = Copy | BYREF = Reference