Predefined Functions (SQA National 5 Computing Science): Revision Note

Exam code: X816 75

Robert Hampton

Written by: Robert Hampton

Reviewed by: James Woodhouse

Updated on

Predefined functions

What is a predefined function?

  • A predefined function is code that carries out a process

  • A user does not need to know how the process is carried out

  • The function performs the task and returns at least one value, often by storing it in a variable

  • These functions are typically built in to high-level (textual) programming languages

Random function

  • The random function is used to generate a random number between two specified numerical limits

  • Random number generation is a programming concept used within a program to add an element of unpredictability

  • Examples of where this concept could be used include:

    • A task may require generating a random value between 1 and 10 to calculate a discount

      • The assignment requires storing a random integer in this range

    • One program design specified selecting a random song to prompt the user to switch on a foam machine

      • Implementing this involves storing a random number equal to the total number of songs entered

    • In a voting app, the function can be used to pick one winning candidate from an array storing the names of candidates who received the same number of votes

    • To select a mystery fruit from a list of ten options, the program generates a random number (e.g., between 0 and 9) to index the fruit from an array of mystery fruits

Syntax

Function

Pseudocode

Python

Random

SET number TO RANDOM(1, 100)

import random

number = random.randint(1,100)

Will pick a number between 1 and 100

Example

  • A National lottery simulation (randomly picking 6 numbers)

SQA Pseudocode

Python

DECLARE LotteryNumbers : ARRAY[1:49] OF INTEGER
DECLARE ChosenNumbers : ARRAY[1:6] OF INTEGER
DECLARE RandomIndex, Number, i, j, Temp : INTEGER

// Populate the LotteryNumbers array
FOR Index FROM 1 TO 49 DO
    SET LotteryNumbers[Index] TO Index
END FOR

// Choose 6 random numbers
FOR Count FROM 1 TO 6 DO
    SET RandomIndex TO ROUND(RANDOM() * (50 - Count), 0)
    IF RandomIndex = 0 THEN
        SET RandomIndex TO 1
    END IF

    SET Number TO LotteryNumbers[RandomIndex]
    SET ChosenNumbers[Count] TO Number

    // Remove chosen number from available list
    FOR i FROM RandomIndex TO 48 DO
        SET LotteryNumbers[i] TO LotteryNumbers[i + 1]
    END FOR
END FOR

// Sort chosen numbers into ascending order
FOR i FROM 1 TO 5 DO
    FOR j FROM i + 1 TO 6 DO
        IF ChosenNumbers[i] > ChosenNumbers[j] THEN
            SET Temp TO ChosenNumbers[i]
            SET ChosenNumbers[i] TO ChosenNumbers[j]
            SET ChosenNumbers[j] TO Temp
        END IF
    END FOR
END FOR

// Display the winning numbers
SEND "The winning numbers are:" TO DISPLAY
FOR i FROM 1 TO 6 DO
    SEND ChosenNumbers[i] TO DISPLAY
END FOR
import random

# Create a list of numbers for the national lottery
lottery_numbers = list(range(1, 50))

# Create an empty list to store the chosen numbers
chosen_numbers = []

# Loop to pick 6 numbers from the list
for _ in range(6):
    # Use random.choice to pick a number from the list
    number = random.choice(lottery_numbers)

    # Add the chosen number to the list of chosen numbers
    chosen_numbers.append(number)

    # Remove the chosen number from the list of available numbers
    lottery_numbers.remove(number)

# Sort the chosen numbers in ascending order
chosen_numbers.sort()

# Output the chosen numbers
print("The winning numbers are:", chosen_numbers)

Round function

  • The round function is used to round a real number to a certain number of decimal places

  • It takes two parameters, the number to be rounded (a real number) and thee number of decimal places to round to

  • Examples of where this concept could be used include:

    • A calculation process might require rounding an average value, such as the average weight of food, to one decimal place

    • A flowchart design illustrated rounding a score to 2 decimal places

    • Students may be tasked with rewriting code to display an average data usage rounded to one decimal place

Syntax

Function

Pseudocode

Python

Round

pi = 3.14159

SET rounded TO ROUND(pi, 2)

SEND rounded TO DISPLAY

// Outputs 3.14

number = 3.14159 rounded_number = round(number, 2)
print(rounded_number)
# Outputs 3.14

Will round the value of pi to 2 decimal places

Example

SQA Pseudocode

Python

DECLARE Price : REAL
DECLARE RoundedPrice : REAL

SET Price TO 12.6789

// Round the value of Price to 2 decimal places
SET RoundedPrice TO ROUND(Price, 2)

SEND "The rounded price is " & RoundedPrice TO DISPLAY
# Declare and assign values
price = 12.6789

# Round the value of price to 2 decimal places
rounded_price = round(price, 2)

# Output the result
print("The rounded price is", rounded_price)

Length function

  • The length function is used to determine and retrieve the size of a data structure

  • It is used to get the length of a string or an array

Syntax

Function

Pseudocode

Python

Length

SET strLength TO LENGTH (str)

number = 3.14159 rounded_number = round(number, 2)
print(rounded_number)
# Outputs 3.14

Stores the length of a string in the variable named strLength

Worked Example

A music promoter is organising a lucky draw for concert attendees.

The names of the 50 individuals eligible to win a backstage pass have been identified and stored temporarily in the program.

State the predefined function that should be used to select one of the 50 stored names for the prize

[1]

Answer

  • random [1 mark]

  • Language specific functions: e.g. randint, rnd [1 mark]

Unlock more, it's free!

Join the 100,000+ Students that ❤️ Save My Exams

the (exam) results speak for themselves:

Robert Hampton

Author: Robert Hampton

Expertise: Computer Science Content Creator

Rob has over 16 years' experience teaching Computer Science and ICT at KS3 & GCSE levels. Rob has demonstrated strong leadership as Head of Department since 2012 and previously supported teacher development as a Specialist Leader of Education, empowering departments to excel in Computer Science. Beyond his tech expertise, Robert embraces the virtual world as an avid gamer, conquering digital battlefields when he's not coding.

James Woodhouse

Reviewer: James Woodhouse

Expertise: Computer Science & English Subject Lead

James graduated from the University of Sunderland with a degree in ICT and Computing education. He has over 14 years of experience both teaching and leading in Computer Science, specialising in teaching GCSE and A-level. James has held various leadership roles, including Head of Computer Science and coordinator positions for Key Stage 3 and Key Stage 4. James has a keen interest in networking security and technologies aimed at preventing security breaches.