S

11.3 Structure Programming

Understanding procedures, functions, parameters, and writing efficient pseudocode

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:

Identifier
total
Parameters
Num1, Num2
Return Type
INTEGER
FUNCTION
total
(
Num1
:
INTEGER
,
Num2
:
INTEGER
)
RETURNS
INTEGER

Real-Life Example: School Library System

In a school library system, you might have:

Procedure Examples:
printOverdueReport() - Prints list of overdue books
sendReminderEmail() - Sends email to students
updateLibraryHours() - Updates opening hours
These perform actions but don't return values
Function Examples:
calculateFine(days) - Returns fine amount
checkAvailability(bookID) - Returns true/false
getStudentBorrowCount(studentID) - Returns number of books
These calculate and return values

Activity 1: Identify Procedure or Function

For each task below, state whether it should be implemented as a procedure or function, and explain why:

  1. Calculate the average of three test scores
  2. Display a welcome message on the screen
  3. Check if a student has passed (score ≥ 50)
  4. Print a student's report card
  5. Convert temperature from Celsius to Fahrenheit
  6. Update a student's attendance record
Solution:
  1. Function - It calculates and returns a value (the average)
  2. Procedure - It performs an action (displaying) but doesn't return a value
  3. Function - It returns a Boolean value (true/false) indicating pass/fail
  4. Procedure - It performs the action of printing a report
  5. Function - It calculates and returns the converted temperature
  6. 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

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
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
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
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
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

PROCEDURE
<ProcedureIdentifier>
(
<parameterList>
)
  <statement(s)>
ENDPROCEDURE
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

CALL
<procedureIdentifier>
(
<argumentList>
)
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
PROCEDURE
Message
(
)
  OUTPUT " CS Made Easy "
ENDPROCEDURE

To call: CALL Message()

Example 2: Procedure with Parameter
PROCEDURE
stars
(
Number
:
INTEGER
)
  FOR Counter 1 TO Number
    OUTPUT "*"
  NEXT Counter
ENDPROCEDURE

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:

PROCEDURE takeOrder(tableNumber, orderItems)
// Records customer order
PROCEDURE printReceipt(tableNumber)
// Prints bill for the table
PROCEDURE updateInventory(item, quantity)
// Updates stock levels
PROCEDURE cleanTable(tableNumber)
// Marks table as available

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

Main Program
CALL Procedure()
Procedure Execution
Return to Main Program

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:

  1. A procedure called printBox that takes two parameters (width and height) and prints a box of asterisks with those dimensions
  2. A procedure called greetUser that takes a username as a parameter and outputs "Hello, [username]!"
  3. A procedure called inputValidAge with no parameters that repeatedly asks for age until a valid age (1-120) is entered
  4. A procedure called calculateAndDisplay that takes three numbers and outputs their sum and average
Solution:
  1. printBox procedure:
    PROCEDURE printBox(width : INTEGER, height : INTEGER)
      DECLARE row, col : INTEGER
      FOR row ← 1 TO height
        FOR col ← 1 TO width
          OUTPUT "*"
        NEXT col
        OUTPUT "" // New line
      NEXT row
    ENDPROCEDURE
  2. greetUser procedure:
    PROCEDURE greetUser(username : STRING)
      OUTPUT "Hello, " + username + "!"
    ENDPROCEDURE
  3. inputValidAge procedure:
    PROCEDURE inputValidAge()
      DECLARE age : INTEGER
      REPEAT
        INPUT "Enter age (1-120): ", age
      UNTIL age >= 1 AND age <= 120
      OUTPUT "Valid age entered: ", age
    ENDPROCEDURE
  4. calculateAndDisplay procedure:
    PROCEDURE calculateAndDisplay(num1 : INTEGER, num2 : INTEGER, num3 : INTEGER)
      DECLARE sum, average : REAL
      sum ← num1 + num2 + num3
      average ← sum / 3
      OUTPUT "Sum = ", sum
      OUTPUT "Average = ", average
    ENDPROCEDURE

Check Your Understanding: Procedures

Answer
  • [1 mark] A procedure should be defined before the main program
  • [Additional] This allows the main program to call the procedure when needed
Answer
  • [1 mark] Using the CALL statement followed by the procedure identifier and arguments
  • [Additional] Example: CALL stars(5) or CALL Message()
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 "*"
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
Answer
PROCEDURE multiply(num1 : INTEGER, num2 : INTEGER)
  DECLARE product : INTEGER
  product ← num1 * num2
  OUTPUT "Product = ", product
ENDPROCEDURE

[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

FUNCTION
<functionIdentifier>
(
<parameterList>
)
RETURNS
<dataType>
  <statement(s)>
  RETURN <value>
ENDFUNCTION
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

<variable>
<functionName>
(
<argumentList>
)
OUTPUT
<functionName>
(
<argumentList>
)
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
FUNCTION
InputOddNumber
(
)
RETURNS
INTEGER
  DECLARE Num : INTEGER
  REPEAT
    INPUT "Enter an odd number: ", Num
  UNTIL Num MOD 2 = 1
  OUTPUT "Valid number entered"
  RETURN Num
ENDFUNCTION

To call: X ← InputOddNumber()

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

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:

FUNCTION calculateSubtotal(cartItems) RETURNS REAL
// Returns sum of item prices
FUNCTION calculateTax(subtotal, taxRate) RETURNS REAL
// Returns tax amount
FUNCTION calculateShipping(weight, destination) RETURNS REAL
// Returns shipping cost
FUNCTION checkDiscount(customerID, purchaseAmount) RETURNS REAL
// Returns discount amount

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:

  1. A function called isEven that takes an integer and returns TRUE if the number is even, FALSE otherwise
  2. A function called calculateCircleArea that takes a radius (REAL) and returns the area of a circle (π × radius²)
  3. A function called getGrade that takes a score (0-100) and returns a grade ("A", "B", "C", "D", or "F") based on standard grading
  4. A function called findMinimum that takes three numbers and returns the smallest one
Solution:
  1. isEven function:
    FUNCTION isEven(number : INTEGER) RETURNS BOOLEAN
      IF number MOD 2 = 0 THEN
        RETURN TRUE
      ELSE
        RETURN FALSE
      ENDIF
    ENDFUNCTION
  2. calculateCircleArea function:
    FUNCTION calculateCircleArea(radius : REAL) RETURNS REAL
      DECLARE area : REAL
      area ← 3.14159 * radius * radius
      RETURN area
    ENDFUNCTION
  3. getGrade function:
    FUNCTION getGrade(score : INTEGER) RETURNS STRING
      IF score >= 90 THEN
        RETURN "A"
      ELSEIF score >= 80 THEN
        RETURN "B"
      ELSEIF score >= 70 THEN
        RETURN "C"
      ELSEIF score >= 60 THEN
        RETURN "D"
      ELSE
        RETURN "F"
      ENDIF
    ENDFUNCTION
  4. findMinimum function:
    FUNCTION findMinimum(a : INTEGER, b : INTEGER, c : INTEGER) RETURNS INTEGER
      DECLARE min : INTEGER
      min ← a
      IF b < min THEN
        min ← b
      ENDIF
      IF c < min THEN
        min ← c
      ENDIF
      RETURN min
    ENDFUNCTION

Check Your Understanding: Functions

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
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
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)
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()
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

Original Variable
X = 10
Copy Created
Copy = 10
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

PROCEDURE
OutputSymbols
(
BYVALUE
NumberOfSymbols
:
INTEGER
,
Symbol
:
CHAR
)
  DECLARE Count : INTEGER
  FOR Count 1 TO NumberOfSymbols
    OUTPUT Symbol
  NEXT Count
ENDPROCEDURE

Call: CALL OutputSymbols(6, '*')

Output: ******

Passing Parameters By Reference

How It Works

Original Variable
X = 10
Memory Address: 0x1000
Pointer Passed
Pointer to 0x1000
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

PROCEDURE
AdjustValuesForNextRow
(
BYREF
Spaces
:
INTEGER
,
BYREF
Symbols
:
INTEGER
)
  Spaces Spaces - 1
  Symbols Symbols + 2
ENDPROCEDURE

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:
calculateInterest(accountBalance, interestRate)
// Calculates interest without changing balance
checkEligibility(customerAge, minAge)
// Checks eligibility without modifying ages
These use values but don't need to change them
BYREF Examples:
depositMoney(BYREF accountBalance, amount)
// Modifies the actual account balance
withdrawMoney(BYREF accountBalance, amount)
// Modifies the actual account balance
These need to modify the original variable

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
DECLARE x : INTEGER
x ← 10
CALL changeValue(x) // x passed BYVALUE
// Inside changeValue: parameter becomes 20
// Outside: x is STILL 10!
BYREF Scenario
DECLARE x : INTEGER
x ← 10
CALL changeValue(x) // x passed BYREF
// Inside changeValue: parameter becomes 20
// Outside: x is NOW 20!

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:

  1. A procedure that prints a student's name and test score
  2. A procedure that swaps the values of two variables
  3. A function that calculates the square of a number
  4. A procedure that increments a counter variable
  5. A function that checks if a password meets security requirements
  6. A procedure that sorts an array of numbers in ascending order
Solution:
  1. BYVALUE - Printing doesn't need to modify the original name or score
  2. BYREF - Swapping requires modifying the original variables
  3. BYVALUE - Calculating square doesn't need to modify the original number
  4. BYREF - Incrementing requires modifying the original counter
  5. BYVALUE - Checking password doesn't need to modify the original password
  6. 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

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
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
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
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
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.

1

ESQ# 1: MakeString() Function

A function MakeString() will:

  1. Take two parameters: a count as an integer and a character
  2. Generate a string of length equal to count, made up of the character
  3. 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:
FUNCTION MakeString(Count : INTEGER, AChar : CHAR) RETURNS STRING
  DECLARE MyString : STRING
  DECLARE Index : INTEGER
  IF Count < 1 THEN
    MyString ← "ERROR"
  ELSE
    MyString ← ""
    FOR Index ← 1 TO Count
      MyString ← MyString & AChar
    NEXT Index
  ENDIF
  RETURN MyString
ENDFUNCTION

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
2

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:
PROCEDURE CountVowels(ThisString : STRING)
  DECLARE Index : INTEGER
  DECLARE ThisChar : CHAR
  
  // Initialize array elements to 0
  FOR Index ← 1 to 6
    CharCount[Index] ← 0
  NEXT Index
  
  // Process each character in the string
  FOR Index ← 1 TO LENGTH(ThisString)
    ThisChar ← LCASE(MID(ThisString, Index, 1))
  
    CASE OF ThisChar
      'a' : CharCount[1] ← CharCount[1] + 1
      'e' : CharCount[2] ← CharCount[2] + 1
      'i' : CharCount[3] ← CharCount[3] + 1
      'o' : CharCount[4] ← CharCount[4] + 1
      'u' : CharCount[5] ← CharCount[5] + 1
      'a' TO 'z' : CharCount[6] ← CharCount[6] + 1
    ENDCASE
  NEXT Index
  
  // Output results
  FOR Index ← 1 to 6
    OUTPUT CharCount[Index]
  NEXT Index
ENDPROCEDURE

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:
FUNCTION isPrime(number : INTEGER) RETURNS BOOLEAN
  DECLARE divisor : INTEGER
  
  // Numbers less than 2 are not prime
  IF number < 2 THEN
    RETURN FALSE
  ENDIF
  
  // Check divisors from 2 to square root of number
  FOR divisor ← 2 TO SQRT(number)
    IF number MOD divisor = 0 THEN
      RETURN FALSE
    ENDIF
  NEXT divisor
  
  RETURN TRUE
ENDFUNCTION
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

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)).
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
Marking Scheme & Answer
FUNCTION calculateGrade(score : INTEGER) RETURNS STRING
  IF score >= 90 THEN
    RETURN "A"
  ELSEIF score >= 80 THEN
    RETURN "B"
  ELSEIF score >= 70 THEN
    RETURN "C"
  ELSEIF score >= 60 THEN
    RETURN "D"
  ELSE
    RETURN "F"
  ENDIF
ENDFUNCTION

[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

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
Marking Scheme & Answer
PROCEDURE printPattern(n : INTEGER)
  DECLARE row, col : INTEGER
  FOR row ← 1 TO n
    FOR col ← 1 TO row
      OUTPUT "*"
    NEXT col
    OUTPUT "" // New line
  NEXT row
ENDPROCEDURE

[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

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).
Marking Scheme & Answer
FUNCTION areAnagrams(str1 : STRING, str2 : STRING) RETURNS BOOLEAN
  DECLARE i : INTEGER
  DECLARE charCount1, charCount2 : ARRAY[1..26] OF INTEGER
  
  // Strings must be same length to be anagrams
  IF LENGTH(str1) ≠ LENGTH(str2) THEN
    RETURN FALSE
  ENDIF
  
  // Initialize character count arrays
  FOR i ← 1 TO 26
    charCount1[i] ← 0
    charCount2[i] ← 0
  NEXT i
  
  // Count characters in first string
  FOR i ← 1 TO LENGTH(str1)
    charCount1[ASC(LCASE(MID(str1, i, 1))) - ASC('a') + 1] ←
    charCount1[ASC(LCASE(MID(str1, i, 1))) - ASC('a') + 1] + 1
  NEXT i
  
  // Count characters in second string
  FOR i ← 1 TO LENGTH(str2)
    charCount2[ASC(LCASE(MID(str2, i, 1))) - ASC('a') + 1] ←
    charCount2[ASC(LCASE(MID(str2, i, 1))) - ASC('a') + 1] + 1
  NEXT i
  
  // Compare character counts
  FOR i ← 1 TO 26
    IF charCount1[i] ≠ charCount2[i] THEN
      RETURN FALSE
    ENDIF
  NEXT i
  
  RETURN TRUE
ENDFUNCTION

[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)

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.
Marking Scheme & Answer
PROCEDURE bubbleSort(BYREF arr : ARRAY[1..n] OF INTEGER)
  DECLARE i, j, temp, n : INTEGER
  n ← LENGTH(arr)
  
  FOR i ← 1 TO n-1
    FOR j ← 1 TO n-i
      IF arr[j] > arr[j+1] THEN
        // Swap elements
        temp ← arr[j]
        arr[j] ← arr[j+1]
        arr[j+1] ← temp
      ENDIF
    NEXT j
  NEXT i
ENDPROCEDURE

[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.

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.