Learning Objectives
By the end of this lesson, you will be able to:
- Define and use a procedure and explain where in construction of an algorithm it would be appropriate to use a procedure
- Use parameters (by value and by reference) in procedures and functions
- Define and use a function and explain where in construction of an algorithm it is appropriate to use a function
- Use terminology associated with procedures and functions (header, parameters, arguments, return type)
- Write efficient pseudocode using procedures and functions
- Understand the advantages of using subroutines in programming
- Distinguish between procedures and functions
- Write pseudocode for procedures and functions with and without parameters
Key Terms
Procedure
A subroutine that groups together a number of steps and gives them a name (identifier). It does not return a value.
Function
A subroutine that groups together steps and returns a single value to the point where it was called.
Parameter
A variable applied to a procedure or function that allows one to pass in a value for the subroutine to use.
Argument
The actual value passed to a procedure or function when it is called.
Header
The first statement in the definition of a procedure or function, containing its name, parameters, and (for functions) return type.
By Value
A method of passing a parameter where a copy of the value is passed; changes inside the subroutine don't affect the original variable.
By Reference
A method of passing a parameter where the memory address is passed; changes inside the subroutine affect the original variable.
Subroutine
A named block of code that performs a specific task (procedure or function).
Decomposition
A problem-solving technique that involves breaking down a complex problem into smaller, more manageable sub-tasks (modules).
Module
A self-contained unit of a program that performs a specific task (can be a procedure or function).
Identifier
The name given to a procedure, function, or variable.
Return Type
The data type of the value that a function returns (e.g., INTEGER, STRING, BOOLEAN).
Modules and Subroutines
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.
Types of Modules
Procedure
A procedure groups together a number of steps and gives them a name known as an identifier. It is defined once and can be called many times within a program.
Characteristics:
- Does not return a value
- Called using CALL statement
- Can have parameters (or none)
- Used for tasks that perform actions
Function
A function groups together a number of steps and gives them a name known as an identifier. Functions operate similarly to procedures, but they return a single value.
Characteristics:
- Returns a single value
- Called as part of an expression
- Must have a return type
- Used for tasks that calculate values
Advantages of Using Subroutines
Benefits for Programmers:
- Reusability: Code can be called from multiple places
- Testing: Can be independently tested and debugged
- Sharing: Enables sharing development between programmers
- Reduced Errors: Less chance of errors as code doesn't need to be rewritten
Benefits for Programs:
- Reduced Duplication: Eliminates unnecessary repetition of code
- Shorter Code: Reduces overall program length
- Easy Maintenance: Changes made only once affect all calls
- Portability: Can be used in multiple programs without rewriting
Real-Life Analogy: Think of subroutines like recipes in a cookbook. Instead of rewriting the recipe for "pancakes" every time you want to make them, you just refer to the recipe page. If you improve the recipe, you update it in one place, and all future pancakes benefit!
Subroutine Header Structure
The first line of a subroutine (function/procedure) is called its header. It includes:
Real-Life Example: School Library System
In a school library system, you might have:
Procedure Examples:
Function Examples:
Activity 1: Identify Procedure or Function
For each task below, state whether it should be implemented as a procedure or function, and explain why:
- Calculate the average of three test scores
- Display a welcome message on the screen
- Check if a student has passed (score ≥ 50)
- Print a student's report card
- Convert temperature from Celsius to Fahrenheit
- Update a student's attendance record
Solution:
- Function - It calculates and returns a value (the average)
- Procedure - It performs an action (displaying) but doesn't return a value
- Function - It returns a Boolean value (true/false) indicating pass/fail
- Procedure - It performs the action of printing a report
- Function - It calculates and returns the converted temperature
- Procedure - It updates data but doesn't return a value
Key Rule: If the task produces a result that will be used in an expression or assignment, use a function. If the task just performs an action, use a procedure.
Check Your Understanding: Modules & Subroutines
1. What is decomposition and why is it useful in programming? [2 marks]
Answer
- [1 mark] Decomposition is a problem-solving technique that involves breaking down a complex problem into smaller, more manageable sub-tasks
- [1 mark] It is useful because it makes complex problems easier to understand, design, test, and maintain
- [Additional] Each sub-task can be implemented as a module (procedure or function) and worked on independently
2. List three advantages of using subroutines in a program. [3 marks]
Answer
- [1 mark] Reusability - subroutine code can be called from multiple places
- [1 mark] Reduces duplication - eliminates unnecessary repetition of program lines
- [1 mark] Easier testing and debugging - subroutines can be tested independently
- [Additional] Other advantages: easier maintenance, shorter code, enables sharing between programmers
3. What is the main difference between a procedure and a function? [2 marks]
Answer
- [1 mark] A function returns a single value to the point where it was called
- [1 mark] A procedure does not return a value (it only performs actions)
- [Additional] Functions are called as part of expressions, procedures are called using CALL statement
4. What information is included in a subroutine header? [3 marks]
Answer
- [1 mark] Identifier (name of subroutine)
- [1 mark] Parameters (values/arguments required to perform task)
- [1 mark] Return data type (for functions only)
- [Additional] Also includes data type of each parameter in the parameter list
5. Why is it beneficial to define a subroutine once and call it many times? [2 marks]
Answer
- [1 mark] Reduces code duplication - same code doesn't need to be written multiple times
- [1 mark] Easier maintenance - if the task needs to change, it only needs to be changed in one place
- [Additional] Also improves consistency and reduces chances of errors from copying code incorrectly
Procedures
A procedure groups together a number of steps and gives them a name known as an identifier. It is defined once and can be called many times within a program. Procedures are defined before the main program and called when needed.
Procedure Syntax
Procedure Definition
Key Points:
- Defined before the main program
- Can have zero, one, or more parameters
- Parameters include data type (e.g., Number : INTEGER)
- Ends with ENDPROCEDURE
Procedure Call
Key Points:
- Called from main program using CALL
- Can be called many times
- Arguments must match parameters in number, type, and order
- When called, statements in procedure body are executed
Procedure Examples Visualizer
Example 1: Procedure without Parameters
To call: CALL Message()
Example 2: Procedure with Parameter
To call: CALL stars(5) or CALL stars(9)
Select an example and click "Simulate" to see the output
Real-Life Example: Restaurant Order System
In a restaurant order system, procedures handle different tasks:
Each procedure performs a specific action without returning a value. They're called throughout the system: CALL takeOrder(5, ["Pizza", "Coke"]), CALL printReceipt(5), etc.
Understanding Procedure Flow
Important: When a procedure is called, program execution jumps to the procedure, runs all its statements, then returns to the point immediately after the CALL statement in the main program.
Activity 2: Write Procedures in Pseudocode
Write pseudocode for the following procedures:
- A procedure called printBox that takes two parameters (width and height) and prints a box of asterisks with those dimensions
- A procedure called greetUser that takes a username as a parameter and outputs "Hello, [username]!"
- A procedure called inputValidAge with no parameters that repeatedly asks for age until a valid age (1-120) is entered
- A procedure called calculateAndDisplay that takes three numbers and outputs their sum and average
Solution:
-
printBox procedure:
PROCEDURE printBox(width : INTEGER, height : INTEGER)DECLARE row, col : INTEGERFOR row ← 1 TO heightFOR col ← 1 TO widthOUTPUT "*"NEXT colOUTPUT "" // New lineNEXT rowENDPROCEDURE -
greetUser procedure:
PROCEDURE greetUser(username : STRING)OUTPUT "Hello, " + username + "!"ENDPROCEDURE -
inputValidAge procedure:
PROCEDURE inputValidAge()DECLARE age : INTEGERREPEATINPUT "Enter age (1-120): ", ageUNTIL age >= 1 AND age <= 120OUTPUT "Valid age entered: ", ageENDPROCEDURE -
calculateAndDisplay procedure:
PROCEDURE calculateAndDisplay(num1 : INTEGER, num2 : INTEGER, num3 : INTEGER)DECLARE sum, average : REALsum ← num1 + num2 + num3average ← sum / 3OUTPUT "Sum = ", sumOUTPUT "Average = ", averageENDPROCEDURE
Check Your Understanding: Procedures
1. Where in a program should a procedure be defined? [1 mark]
Answer
- [1 mark] A procedure should be defined before the main program
- [Additional] This allows the main program to call the procedure when needed
2. How is a procedure called in pseudocode? [1 mark]
Answer
- [1 mark] Using the CALL statement followed by the procedure identifier and arguments
- [Additional] Example: CALL stars(5) or CALL Message()
3. What is the output when CALL stars(3) is executed? [2 marks]
Answer
- [1 mark] The procedure prints 3 asterisks in a row
- [1 mark] Output: ***
- [Additional] The FOR loop runs 3 times (Counter from 1 to 3), each time outputting "*"
4. What is the difference between a parameter and an argument? [2 marks]
Answer
- [1 mark] A parameter is a variable in the procedure definition (e.g., Number : INTEGER)
- [1 mark] An argument is the actual value passed when the procedure is called (e.g., 5 in CALL stars(5))
- [Additional] Parameters are placeholders; arguments are the actual values that fill those placeholders
5. Write a procedure definition for a procedure that takes two integers and outputs their product. [3 marks]
Answer
[1 mark] Correct procedure header with parameters
[1 mark] Correct calculation of product
[1 mark] Correct output statement
Functions
A function groups together a number of steps and gives them a name known as an identifier. Functions operate similarly to procedures, but they return a single value to the point where they are called. Function definition includes the data type of the value returned.
Function Syntax
Function Definition
Key Points:
- Must specify RETURNS <dataType>
- Must include at least one RETURN statement
- Can have multiple RETURN statements (different paths)
- Ends with ENDFUNCTION
Function Call
Key Points:
- DO NOT use CALL for functions
- Called as part of an expression
- Return value can be assigned to a variable or used directly
- Example: X ← InputOddNumber() or OUTPUT Max(10, 2)
Function Examples Visualizer
Example 1: InputOddNumber Function
To call: X ← InputOddNumber()
Example 2: Max Function
To call: OUTPUT "Max Number is = ", Max(10, 2)
Select an example and click "Simulate" to see the return value
Real-Life Example: E-commerce Shopping Cart
In an e-commerce system, functions calculate various values:
These functions return values that are used in calculations: total ← calculateSubtotal(cart) + calculateTax(subtotal, 0.08) + calculateShipping(weight, "UK") - checkDiscount(customerID, subtotal)
Critical Difference: Procedure vs Function Calls
| Aspect | Procedure Call | Function Call |
|---|---|---|
| Syntax | CALL procedureName(args) | variable ← functionName(args) or use in expression |
| Returns Value | No | Yes (single value) |
| Used in Expressions | Cannot be used in expressions | Can be used in expressions |
| Example | CALL printStars(5) | result ← calculateAverage(85, 90, 78) |
| Common Error | Forgetting CALL keyword | Using CALL keyword (WRONG!) |
Remember: If you need to use the result in an expression or assignment, use a function. If you just need to perform an action, use a procedure.
Activity 3: Write Functions in Pseudocode
Write pseudocode for the following functions:
- A function called isEven that takes an integer and returns TRUE if the number is even, FALSE otherwise
- A function called calculateCircleArea that takes a radius (REAL) and returns the area of a circle (π × radius²)
- A function called getGrade that takes a score (0-100) and returns a grade ("A", "B", "C", "D", or "F") based on standard grading
- A function called findMinimum that takes three numbers and returns the smallest one
Solution:
-
isEven function:
FUNCTION isEven(number : INTEGER) RETURNS BOOLEANIF number MOD 2 = 0 THENRETURN TRUEELSERETURN FALSEENDIFENDFUNCTION -
calculateCircleArea function:
FUNCTION calculateCircleArea(radius : REAL) RETURNS REALDECLARE area : REALarea ← 3.14159 * radius * radiusRETURN areaENDFUNCTION -
getGrade function:
FUNCTION getGrade(score : INTEGER) RETURNS STRINGIF score >= 90 THENRETURN "A"ELSEIF score >= 80 THENRETURN "B"ELSEIF score >= 70 THENRETURN "C"ELSEIF score >= 60 THENRETURN "D"ELSERETURN "F"ENDIFENDFUNCTION -
findMinimum function:
FUNCTION findMinimum(a : INTEGER, b : INTEGER, c : INTEGER) RETURNS INTEGERDECLARE min : INTEGERmin ← aIF b < min THENmin ← bENDIFIF c < min THENmin ← cENDIFRETURN minENDFUNCTION
Check Your Understanding: Functions
1. What keyword should never be used when calling a function? [1 mark]
Answer
- [1 mark] The CALL keyword should never be used when calling a function
- [Additional] Functions should only be called as part of an expression or assignment statement
2. What must every function definition include that a procedure does not? [2 marks]
Answer
- [1 mark] A RETURNS <dataType> clause in the header
- [1 mark] At least one RETURN statement in the body
- [Additional] The return type specifies what type of value the function will return
3. Write two different ways to call the Max function from the examples. [2 marks]
Answer
- [1 mark] Assignment: largest ← Max(10, 2)
- [1 mark] In output: OUTPUT "Max Number is = ", Max(10, 2)
- [Additional] Also: IF Max(a, b) > 50 THEN ... (in condition)
4. What is wrong with this function call: CALL InputOddNumber()? [2 marks]
Answer
- [1 mark] InputOddNumber() is a function (returns a value)
- [1 mark] Functions should not be called with CALL; they should be called as part of an expression
- [Additional] Correct way: X ← InputOddNumber()
5. What value is returned by SumRange(1, 5) from the example? [2 marks]
Answer
- [1 mark] The function calculates the sum of integers from 1 to 5
- [1 mark] Returns: 1 + 2 + 3 + 4 + 5 = 15
- [Additional] The FOR loop adds each value from FirstValue to LastValue to the Sum variable
Parameters: By Value vs By Reference
Parameters can be passed to subroutines in two ways: by value and by reference. Understanding the difference is crucial for writing correct programs.
Passing Parameters By Value
How It Works
Key Characteristics:
- A copy of the value is passed to the subroutine
- If argument is a variable, a copy of its current value is passed
- Changes inside subroutine do not affect original variable
- Used when you don't want the original value changed
Example: BYVALUE Parameter
Call: CALL OutputSymbols(6, '*')
Output: ******
Passing Parameters By Reference
How It Works
Key Characteristics:
- A pointer (memory address) is passed to the subroutine
- Argument must be a variable (not a constant)
- Changes inside subroutine affect original variable
- Used when you want to modify the original value
Example: BYREF Parameter
Before call: NumberOfSpaces = 5, NumberOfSymbols = 1
Call: CALL AdjustValuesForNextRow(NumberOfSpaces, NumberOfSymbols)
After call: NumberOfSpaces = 4, NumberOfSymbols = 3
By Value vs By Reference Comparison
| Aspect | By Value (BYVALUE) | By Reference (BYREF) |
|---|---|---|
| What is passed | Copy of the value | Pointer to memory location |
| Argument type | Can be variable or constant | Must be a variable |
| Effect on original | No effect (changes inside subroutine don't affect original) | Direct effect (changes inside subroutine affect original) |
| Memory usage | Uses more memory (creates copy) | Uses less memory (shares memory) |
| When to use | When you don't want original changed | When you need to modify original |
| Example | PROCEDURE PrintNum(BYVALUE n : INTEGER) | PROCEDURE DoubleNum(BYREF n : INTEGER) |
Click "Simulate Both Methods" to see how values change differently with BYVALUE and BYREF
Real-Life Example: Bank Account System
In a bank account system, different parameter passing methods are used for different operations:
BYVALUE Examples:
BYREF Examples:
If depositMoney used BYVALUE, it would change a copy of the balance, not the actual balance!
Common Student Confusion
Students often think: "If I pass a variable to a subroutine, changes inside will always affect the original." This is WRONG! It depends on whether you use BYVALUE or BYREF.
BYVALUE Scenario
BYREF Scenario
Key Question to Ask: "Do I need the subroutine to modify the original variable?" If YES → BYREF. If NO → BYVALUE.
Activity 4: Identify Parameter Passing Method
For each scenario, state whether parameters should be passed BYVALUE or BYREF, and explain why:
- A procedure that prints a student's name and test score
- A procedure that swaps the values of two variables
- A function that calculates the square of a number
- A procedure that increments a counter variable
- A function that checks if a password meets security requirements
- A procedure that sorts an array of numbers in ascending order
Solution:
- BYVALUE - Printing doesn't need to modify the original name or score
- BYREF - Swapping requires modifying the original variables
- BYVALUE - Calculating square doesn't need to modify the original number
- BYREF - Incrementing requires modifying the original counter
- BYVALUE - Checking password doesn't need to modify the original password
- BYREF - Sorting requires modifying the original array
General Rule: Use BYREF when the subroutine needs to modify the original variable(s). Use BYVALUE when the subroutine only needs to use the value(s) without modifying them.
Check Your Understanding: Parameters
1. What is the key difference between passing by value and passing by reference? [2 marks]
Answer
- [1 mark] By value passes a copy of the value; by reference passes a pointer to the memory location
- [1 mark] Changes to parameters passed by value don't affect the original; changes to parameters passed by reference do affect the original
- [Additional] By value uses BYVALUE keyword; by reference uses BYREF keyword in pseudocode
2. When passing by reference, what must the argument be? [1 mark]
Answer
- [1 mark] When passing by reference, the argument must be a variable (cannot be a constant or expression)
- [Additional] This is because by reference needs a memory address to point to, and only variables have memory addresses
3. What will be the values of A and B after this code executes? [3 marks]
Answer
- [1 mark] A = 10
- [1 mark] B = 5
- [1 mark] The values are swapped because parameters are passed BYREF
- [Additional] If parameters were passed BYVALUE, A would still be 5 and B would still be 10 after the call
4. Why would you choose to pass a parameter by value instead of by reference? [2 marks]
Answer
- [1 mark] To protect the original value from being accidentally changed by the subroutine
- [1 mark] When the subroutine only needs to use the value without modifying it
- [Additional] Also for safety and clarity - BYVALUE makes it clear the subroutine won't modify the original
5. Can you pass a constant (like 5 or "hello") by reference? Explain. [2 marks]
Answer
- [1 mark] No, you cannot pass a constant by reference
- [1 mark] By reference requires a memory address, and constants don't have memory addresses that can be modified
- [Additional] Attempting to pass a constant by reference would cause an error because the subroutine might try to modify it, which is impossible for a constant
Exam Style Questions
These questions are based on actual exam questions and test your understanding of procedures, functions, and parameters.
ESQ# 1: MakeString() Function
A function MakeString() will:
- Take two parameters: a count as an integer and a character
- Generate a string of length equal to count, made up of the character
- Return the string generated, or return "ERROR" if the count is less than 1
For example, function call: MakeString(3, 'Z') will return string "ZZZ"
Write pseudocode for function MakeString().
Solution:
Key Points:
- Correct function header with parameters and return type
- Checks if Count < 1 and returns "ERROR"
- Uses FOR loop to concatenate character Count times
- Uses string concatenation operator (&)
- Returns the generated string
ESQ# 2: CountVowels() Procedure
A procedure CountVowels() will:
- Be called with a string containing alphanumeric characters as its parameter
- Count and output number of occurrences of each vowel (a, e, i, o, u) in string
- Count and output the number of occurrences of the other alphabetic characters (as a single total)
String may contain both upper and lower case characters.
Each count value will be stored in a unique element of global 1D array CharCount of type INTEGER. Array will contain six elements.
Write pseudocode for procedure CountVowels().
Solution:
Key Points:
- Correct procedure header with string parameter
- Initializes all array elements to 0 first
- Uses LCASE() to handle both uppercase and lowercase
- Uses CASE statement to categorize characters
- CharCount[1]-[5] store vowel counts, CharCount[6] stores other letters
- Outputs all counts at the end
Interactive Pseudocode Practice
Practice writing pseudocode for this function. Check your solution against the model answer.
Problem:
Write a function called isPrime that takes an integer parameter and returns TRUE if the number is prime, FALSE otherwise. A prime number is only divisible by 1 and itself.
Your Solution:
Model Solution:
Explanation:
- Function header: Correct return type (BOOLEAN) and parameter
- Edge cases: Handles numbers less than 2 (not prime)
- Efficiency: Only checks divisors up to square root of number (mathematically correct and efficient)
- MOD operator: Uses MOD to check divisibility
- Return statements: Returns FALSE if any divisor found, TRUE otherwise
- Alternative valid solution: Could check divisors from 2 to number-1 (less efficient but still correct)
Write your solution and click "Check Solution" to get feedback
Key Takeaways
- Decomposition breaks complex problems into smaller, manageable sub-tasks called modules
- Procedures group steps together, are called with CALL, perform actions but don't return values
- Functions group steps together, return a single value, are called as part of expressions (not with CALL)
- Parameters are variables in subroutine definitions; arguments are actual values passed when calling
- BYVALUE passes a copy of the value; changes inside subroutine don't affect original variable
- BYREF passes a pointer to memory location; changes inside subroutine affect original variable
- Subroutine advantages include reusability, reduced duplication, easier testing, and easier maintenance
- Procedure syntax: PROCEDURE name(parameters) ... ENDPROCEDURE, called with CALL name(arguments)
- Function syntax: FUNCTION name(parameters) RETURNS type ... RETURN value ... ENDFUNCTION
- Function must have at least one RETURN statement and specify return type in header
- Order matters: Arguments must match parameters in number, type, and order (subroutine interface)
- Efficient pseudocode uses subroutines to avoid repetition and make code more readable/maintainable
- Choose procedure vs function: Use function if you need to return a value for use in expression; use procedure for actions
- Choose BYVALUE vs BYREF: Use BYREF if subroutine needs to modify original variable; use BYVALUE otherwise
Question Bank
1. Explain the difference between a procedure and a function, giving an example of when you would use each. [4 marks]
Marking Scheme & Answer
- [2 marks] Procedure: Groups steps, performs actions, doesn't return a value. Called with CALL. Example: Printing output, reading input, displaying menu.
- [2 marks] Function: Groups steps, returns a single value. Called as part of expression. Example: Calculating average, checking validity, converting units.
- [Additional] Use procedure for actions (e.g., CALL printReport()). Use function for calculations (e.g., grade ← calculateGrade(score)).
2. Describe three advantages of using subroutines in a program. [3 marks]
Marking Scheme & Answer
- [1 mark] Reusability: Code can be called from multiple places without rewriting
- [1 mark] Reduced duplication: Eliminates repetition of code, making programs shorter
- [1 mark] Easier maintenance: Changes made in one place affect all calls
- [Additional] Other advantages: easier testing/debugging, enables sharing between programmers, reduces errors from copying code
3. Write pseudocode for a function called calculateGrade that takes a test score (0-100) and returns a letter grade based on: 90+ = "A", 80-89 = "B", 70-79 = "C", 60-69 = "D", below 60 = "F". [5 marks]
Marking Scheme & Answer
[1 mark] Correct function header with parameter and return type
[1 mark] Uses IF/ELSEIF/ELSE structure
[1 mark] Correct conditions for each grade range
[1 mark] Correct return values (strings)
[1 mark] Proper indentation and ENDFUNCTION
4. What will be the output of the following pseudocode? Explain why. [4 marks]
Marking Scheme & Answer
- [2 marks] Output: x = 5, y = 20
- [1 mark] x remains 5 because it's passed BYVALUE - changes to a inside procedure don't affect x
- [1 mark] y becomes 20 because it's passed BYREF - changes to b inside procedure affect y (10 × 2 = 20)
- [Additional] Key understanding: BYVALUE passes copy, BYREF passes reference to original
5. Write a procedure called printPattern that takes an integer parameter n and prints a right-angled triangle of asterisks with n rows. [5 marks]
Example: CALL printPattern(4) outputs:
*
**
***
****
Marking Scheme & Answer
[1 mark] Correct procedure header with parameter
[1 mark] Outer FOR loop for rows (1 to n)
[1 mark] Inner FOR loop for columns (1 to row)
[1 mark] Correct output of asterisks
[1 mark] Output new line after each row
[Alternative] Could use string concatenation instead of nested loop
6. Explain what is meant by "subroutine interface" and why the order of parameters is important. [3 marks]
Marking Scheme & Answer
- [1 mark] Subroutine interface: The connection between a subroutine call and its definition, involving parameters and arguments
- [1 mark] Order importance: Arguments are assigned to parameters based on their position in the lists
- [1 mark] Consequence: If order is wrong, arguments go to wrong parameters, causing incorrect results or errors
- [Additional] Example: CALL total(5, 9) assigns 5 to first parameter, 9 to second parameter. Must match PROCEDURE total(Num1, Num2).
7. Write pseudocode for a function that takes two strings as parameters and returns TRUE if they are anagrams (contain same letters in different order), FALSE otherwise. [6 marks]
Marking Scheme & Answer
[1 mark] Correct function header
[1 mark] Checks if strings are same length
[1 mark] Initializes character count arrays
[1 mark] Counts characters in both strings (handles case)
[1 mark] Compares character counts
[1 mark] Returns TRUE if all counts match
[Simpler alternative] Could sort both strings and compare (less efficient but simpler)
8. What is the difference between a parameter and an argument? Give an example. [3 marks]
Marking Scheme & Answer
- [1 mark] Parameter: Variable in subroutine definition that receives value (placeholder)
- [1 mark] Argument: Actual value passed to subroutine when called
- [1 mark] Example: In PROCEDURE stars(Number : INTEGER), Number is parameter. In CALL stars(5), 5 is argument.
- [Additional] Parameters are defined; arguments are supplied. Parameters have data types; arguments are values.
9. Write pseudocode for a procedure that takes an array of integers and sorts it in ascending order using the bubble sort algorithm. [6 marks]
Marking Scheme & Answer
[1 mark] Correct procedure header with BYREF parameter (modifies original array)
[1 mark] Gets length of array
[1 mark] Outer loop for passes (1 to n-1)
[1 mark] Inner loop for comparisons (1 to n-i)
[1 mark] Compares adjacent elements
[1 mark] Correct swapping logic with temp variable
[Note] Bubble sort is O(n²) but simple to implement. Must use BYREF to modify original array.
10. Why must a function definition include a RETURN statement, and why can there be more than one? [3 marks]
Marking Scheme & Answer
- [1 mark] A function must return a value to the calling code, so it needs at least one RETURN statement
- [1 mark] There can be more than one RETURN statement if there are different paths through the function
- [1 mark] Example: IF/ELSE structure where different conditions return different values
- [Additional] In the Max function example: IF Number1 > Number2 THEN RETURN Number1 ELSE RETURN Number2 ENDIF. Two RETURN statements for two paths.