Subtopic Notes

10.1 Data Types and Records

10. Data Types and Structures

Chapter 10, 11 - Programming, Data Types and Structures

Programming is the process of writing instructions in a language a computer can understand to solve problems or perform tasks. It is a transferable skill, meaning the skills developed for one scenario can be easily transferred to another.

Algorithm

Solution to a problem expressed as a sequence of defined steps

Stages of Computer Program

  • Input: Takes in values from the user to the program
  • Storage: Temporarily or permanently saves data for use during or after program execution
  • Process: Operations that transform inputs into outputs
  • Output: Displays values to the user

Output

PythonPseudocode
#print(Values) print("Hello World!") print("CS is fun!") print(358) print(3 + 3) print(2 * 5)//OUTPUT <value(s)> OUTPUT "Hello World" OUTPUT "CS is fun!" OUTPUT 358 OUTPUT 3 + 3 OUTPUT 2 * 5

Comments

You may wish to write something in the code which the computer will ignore which is why comments are needed. Text written in a program but not run by the computer is called a comment. These are basically used to explain why a part of code is used, help other people reading the code understand it faster, or Ignore a line of code.

## This is a comment in python
// This is a comment in pseudocode

Variable

  • Name given to a distinct memory location and contains a value
  • Can be updated throughout the program

Constant

  • Name given to a distinct memory location and contains a value
  • Cannot be updated once it is created

Data Types

  • INTEGER: Represents a whole number, positive or negative
  • REAL: Represents a floating point number
  • CHAR: Represents a character, surrounded by single quotes (‘A’)
  • STRING: Sequence of characters, surrounded by “double quotes”
  • BOOLEAN: The logical values True or False
  • DATE: Represents a valid calendar date. May use dd/mm/yyyy
  • ARRAY: A List of same data type
  • FILE: Resource for recording data in a computer
  • NULL: No Value
# Variable declarations and initializations name = "Nehal" marks = 40 total = 50 #Updating variable values grade = 'C' grade = 'A' raw_marks = 84.8 passed = True # Printing values print("Hello " + name) print("Your marks are: " + str(marks)) # Concatenating strings last_name = "Nehal" full_name = "Maknun" + " " + last_name print(full_name) # Calculating percentage percentage = (marks / total) * 100 # Multiple assignments a = b = c = 125 x, y, z = "A", "B", "C" sum_of_numbers = a + b + c print("Sum of numbers: " + str(sum_of_numbers)) #Constant in python #Use all uppercase and _ to separate words SPEED_OF_LIGHT = 299792458
Pseudocode
You need to explicitly declare variables in pseudocode with the appropriate data type. Values are assigned late in the code using the assignment operator. If you write python, you need to mention data types as comments //Declaration Statements //DECLARE <identifier> : <data type> DECLARE Index : INTEGER DECLARE Average : REAL DECLARE Name : BOOLEAN //For Constant //CONSTANT <identifier> = <value> //CONSTANT SPEED_OF_LIGHT = 299792458 //Only literals can be used as the value of a constant. A variable,another //constant or an expression must never be used. //Assignment Statements //<identifier> ← <value> Index ← 0 Average ← 60 Name ← "Nehal" Index ← Index + 1

Identifier

  • Name given to an entity distinctly identifying an entity in a program
  • Variable names, function names, class names all are identifiers
  • Rules
    • Must be unique
    • Cannot have spaces
    • Must begin with a letter
    • Can consist of letters, digit or underscore
    • Reserved words in the language cannot be used (You’ll notice that in pseudocode, keywords are all written in upper-case)
    • Names are case sensitive

Identifier Table

Table that stores information about identifiers (such as variables, functions, or objects) in a program, typically including their names, types, and attributes or description. Each identifier will be represented in each row.

Input

PythonPseudocode
#The value will be set to the variable name name = input("Enter a name: ") #For values except string, mention data type num1 = int(input("Enter first number: ")) num2 = float(input("Enter second number: "))INPUT <identifier> OUTPUT "Enter a name: " INPUT name INPUT num1 INPUT num2

Operators

  • An operator is a symbol or keyword in programming that tells the computer to perform a specific operation on one or more values (called operands)
  • May be used to compare types REAL/FLOAT and INTEGER
  • May be used to compare types CHAR and STRING
  • Case sensitive when used to compare types CHAR and/or STRING
  • Cannot be used to compare two records or object

Arithmetic operators

OperatorNameDescriptionPythonPseudocode
+AdditionAdds together two valuesa + b
-SubtractionSubtracts one value from anothera - b
*MultiplicationMultiplies two valuesa * b
/DivisionDivides one value by anothera / y
%ModulusReturns the division remaindera % yA MOD b
**ExponentReturns a to the power of ba ** bNot supported
/ /Floor DivideDivide & return the whole numbera // ba DIV b

Assignment operators

OperatorExamplePseudocode
=a = 5a ← 5
<operator>=a += 5 (Represents a = a + 5)Not supported

Comparison operators

Returns a boolean value

PythonPseudocodeDescription
var == var=Equal to
var != var<>Not Equal
<, >, <=, >=<, >, <=, >=Greater/Less than (or equal to)

Logical operators

Works similar to logic gates

OperatorNamePseudocodeExample (Pseudocode)
andLogical andANDa > 9 AND a < 25
orLogical orORa > 9 OR a <25
notLogical NotNOTNOT (a = 25)

Precedence

Sets the rule on the order of operators

OperatorName
()Parentheses
**Exponent
* / // %Multiplication, Division, Floor Division, Modulus
+ -Addition, Subtraction
== != > < <= >=Comparison Operators
notLogical NOT
andLogical AND
orLogical OR

Conditional/Selection Statements

  • Allows a program to make decisions and execute different blocks of code based on certain conditions
  • Selects specific paths depending on the evaluation of boolean expressions

IF Statements

PythonPseudocode
marks = 85 if marks >= 50: print("You passed!")marks ← 85 IF marks >= 50 THEN OUTPUT "You passed!" ENDIF

Indentation: Lines are indented (usually by three spaces) to indicate that they are contained within a statement in a previous line. Notice how in the condition statements, after the conditions are give, there are some blank spaces

Else Statements

Executes one block if the condition is true, another if it's false.

PythonPseudocode
marks = 40 if marks >= 50: print("You passed!") else: print("You failed.")marks ← 40 IF marks >= 50 THEN OUTPUT "You passed!" ELSE OUTPUT "You Failed!" ENDIF

Elif Statements

PythonPseudocode
marks = 85 if marks >= 90: print("Grade: A+") elif marks >= 80: print("Grade: A") elif marks >= 70: print("Grade: B") else: print("Grade: F")marks ← 85 IF marks >= 90 THEN OUTPUT "Grade: A+" ELSE IF marks >= 80 THEN OUTPUT "Grade: A" ELSE IF marks >= 70 THEN OUTPUT "Grade: B" ELSE OUTPUT "Grade: F" END IF

Nested If

The same program like above is now being done with nested if statements

marks = 85 if marks >= 90: print("Grade: A+") else: if marks >= 80: print("Grade: A") else: if marks >= 70: print("Grade: B") else: print("Grade: F")

Pass Statement (Do Nothing)

marks = 85 if marks >= 90: pass #Skips this line

Logical Operators

x = 50 y = 80 z = 25 if x > z or y > z: print("One of the condition is true") if x > z and y > z: print("Both of the conditions are true") if not x > z: print("x is not greater than z")

CASE Statements

The match-case statement gives a more readable and efficient way to handle multiple conditions

print("Select operation from Below:") print("1.Addition") print("2.Subtraction") print("3.Multiplication") print("4.Division") print("") choice = input("Enter choice: ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) match choice: case '1': print(num1, "+", num2, "=", num1 + num2) case '2': print(num1, "-", num2, "=", num1 - num2) case '3': print(num1, "*", num2, "=", num1 * num2) case '4': if num2 != 0: print(num1, "/", num2, "=", num1 / num2) else: print("Error: Division by zero is not allowed.") case _: #Default Case print("Invalid choice. Please enter 1, 2, 3, or 4.")
Pseudocode
INPUT Move CASE OF Move ꞌWꞌ : Position ← Position − 10 ꞌSꞌ : Position ← Position + 10 ꞌAꞌ : Position ← Position − 1 ꞌDꞌ : Position ← Position + 1 OTHERWISE : CALL Beep() ENDCASE

Iteration/Loops

Iteration is used when you want to execute a block of code repeatedly. The code is repeated for a specified number of times or until a condition is met.

Count-Controlled Iteration

The code is repeated a fixed number of times. You should use it when you know exactly how many times a block will loop. It clearly expresses the variable initialization, condition and increment in one line (Best for incrementing through an array).

range(start, stop, step)

  • start (optional):
    • Starting value of the sequence.
    • Inclusive
    • Default Value 0
  • stop (required):
    • The endpoint of the sequence
    • Exclusive
  • step (optional):
    • The difference between each number in the sequence
    • Defaults Value: 1
#Prints the line 5 times for i in range(5): print("All is well") #Prints 0 to 99 for i in range(100): print(i) #Prints 1 to 100 for i in range(1, 101): print(i) #Prints even numbers from 1 to 100 for i in range(1, 101, 2): print(i) #Prints multiples of 5 from 1 to 100 for i in range(1, 101): if i % 5 == 0: print(i) #Prints 100 to 1 for i in range(100, 0, -1): print(i) #Multiplication table of 5 for i in range(1, 11): print(5 ,'x', i, '=', 5*i) #Finding factors of num num = int(input("Enter a number: ")) for i in range(1, num + 1): if num % i == 0: print(i)
Pseudocode
FOR <identifier> ← <value1> TO <value2> <statement(s)> NEXT <identifier> FOR <identifier> ← <value1> TO <value2> STEP <increment> <statement(s)> NEXT <identifier> //All <values> are integer, <increment> may be negative

Pre-Conditioned Loops

  • The condition is checked before each iteration
  • The loop executes only if the condition is true.
  • May execute zero times if the condition is false initially
  • Useful for indefinite loops or when the condition may initially be false
# Prints even numbers from 1 to 100 i = 1 while i <= 100: print(i) i += 2 # Prints 100 to 1 i = 100 while i > 0: print(i) i -= 1 # Multiplication table of 5 i = 1 while i <= 10: print(5, 'x', i, '=', 5 * i) i += 1 # Finding factors of num num = int(input("Enter a number: ")) i = 1 while i <= num: if num % i == 0: print(i) i += 1 while True: #Runs the block until x is input user_input = input("Enter something (type 'x' to exit): ") if user_input == "x": break print("You entered:", user_input)
Pseudocode
WHILE <condition> DO <statements> ENDWHILE

Post-Conditioned Loops

  • Condition is checked after the block of code executes
  • Executes at least once regardless of the condition
  • Not available in python
REPEAT <statement(s)> UNTIL <condition> REPEAT OUTPUT "Please enter the password" INPUT Password UNTIL Password = "Secret" // Prints 0 to 99 i ← 0 REPEAT OUTPUT i i ← i + 1 UNTIL i = 100 // Prints 100 to 1 i ← 100 REPEAT OUTPUT i i ← i - 1 UNTIL i = 0 // Finding factors of num INPUT num i ← 1 REPEAT IF num MOD i = 0 THEN OUTPUT i ENDIF i ← i + 1 UNTIL i > num

Infinite Loops: A loop that continues to execute endlessly because its termination condition is never met or there is no condition to stop it. It might cause the program to freeze so always make sure to change values of variables when needed. Some infinite loops might be intentional (eg. waiting for an input)

while True: #Example of infinite loop print("This is an infinite loop!")

Nested Statements

  • Different types of constructs can be placed one inside another using indentation
  • It helps to minimize code duplication and makes testing easier

Arrays

  • Stores a collection of elements of the same data type
  • Contiguous block of memory
  • Widely used in programming because they allow efficient access and manipulation of a large number of values
  • Elements can be accessed using index
  • Advantages: Fast insertion, Fast access of elements
  • Disadvantages: Slow search, Slow deletion, Fixed size
  • Ordered Arrays: Elements are arranged in a specific order based on values
    • Advantage: More efficient search algorithm
    • Disadvantage: Slow deletion, slow insertion, fixed size
  • Arrays are 0 indexed: Index of 1st element is 0, 2nd element is 1
  • Index of last element: length - 1
  • In Pseudocode, Arrays index might start from 0 or 1
car_companies = ["Toyota", "Ford","Audi","Ferrari","Lamborghini"] a = car_companies[0] #Setting a to the 1st element car_companies[1] = "Mazda" #Modifying value of the 2nd element length = len(car_companies) #Returns the number of element #Looping through elements of array and printing for car in car_companies : print(car) #Looping through array elements using index for i in range(len(car_companies)): print(car_companies[i]) #Not supported in pseudocode car_companies.append("Honda") #Adds a new value to array car_companies.pop(2) #Removes the third element
Pseudocode
// DECLARE <identifier>:ARRAY[<lower>:<upper>] OF <data type> // lower is the index of 1st element // upper is the index of last element DECLARE StudentNames : ARRAY[1:30] OF STRING StudentNames[1] ← "Ali" //Setting value of an element StudentNames[n+1] ← StudentNames[n] //Setting value of nth element to (n+1)th element //Arrays can be used in assignment statements (provided they have the same //size and data type). The following is therefore allowed: SavedGame ← NoughtsAndCrosses // Example – assigning a group of array elements FOR Index ← 1 TO 30 StudentNames[Index] ← "" NEXT Index

Common Array Operations

numbers = [0, 6, 7, 96, 6, 5, 6, 0, 6, 4, 95, 2, 3] sum = 0 average = 0 length = len(numbers) countZeros = 0 #Setting this to a very small value and updating value when we find something larger largest = 0 #Setting this to a very large value and updating value when we find something smaller smallest = 9999 for item in numbers: if item == 0: countZeros = countZeros + 1 if item > largest: largest = item if item < smallest: smallest = item sum = sum + item average = sum / length print("Length:", length, "Sum:", sum, "Largest:", largest, "Smallest:", smallest, "Average:", average)
Pseudocode
DECLARE Numbers : ARRAY[1:13] OF INTEGER DECLARE Sum, LengthArr, CountZeros, Largest, Smallest : INTEGER DECLARE Average: REAL Numbers ← [0, 6, 7, 96, 6, 5, 6, 0, 6, 4, 95, 2, 3] Sum ← 0 Average ← 0 LengthArr ← 13 CountZeros ← 0 Largest ← 0// Setting this to a very small value Smallest ← 9999 // Setting this to a very large value FOR index ← 1 TO 13 IF Numbers[index] = 0 THEN CountZeros ← CountZeros + 1 ENDIF IF Numbers[index] > Largest THEN Largest ← Numbers[index] ENDIF IF Numbers[index] < Smallest THEN Smallest ← Numbers[index] ENDIF Sum ← Sum + Numbers[index] NEXT index Average ← Sum / LengthArr OUTPUT "Sum: ", Sum OUTPUT "Largest: ", Largest OUTPUT "Smallest: ", Smallest OUTPUT "Average: ", Average

Linear Search

Simple searching algorithm that checks each element in a list or array sequentially until it finds the desired value

Python
numbers = [0, 6, 7, 96, 6, 5, 6, 0, 6, 4, 95, 2, 3] target = 95 #Number to search foundIndex = -1 for index in range(len(numbers)): if numbers[index] == target: foundIndex = index break if foundIndex == -1: print("Not Found") else: print("Found at index:" , foundIndex)
Pseudocode
DECLARE data : ARRAY[1:5] OF INTEGER DECLARE target : INTEGER DECLARE found : BOOLEAN data ← [5, 2, 8, 1, 9] target ← 1 found ← FALSE // Loop through each element in the array FOR index ← 1 TO 5 // Check if the current element matches the target IF data[index] = target THEN found ← TRUE OUTPUT "Target found" ENDIF NEXT index IF found = FALSE THEN OUTPUT "Target not found" ENDIF

Bubble Sort

Sorting algorithm that repeatedly swaps adjacent elements if they are in the wrong order and iterates until the list is sorted.

Python
numbers = [0, 6, 7, 96, 6, 5, 6, 0, 6, 4, 95, 2, 3] # Outer loop to iterate through the list n times for i in range(len(numbers) - 1, 0, -1): swapped = False # Inner loop to compare adjacent elements for j in range(i): if numbers[j] > numbers[j + 1]: temp = numbers[j] numbers [j] = numbers[j + 1] numbers[j + 1] = temp swapped = True # If no swaps occurred, the list is already sorted if not swapped: break print(numbers) #Shows the sorted array
Pseudocode
// Assuming array is declared as num, length declared as numLength // Set a flag to check if any swaps are made DECLARE swaps : BOOLEAN swaps ← TRUE // Repeat the loop while swaps are being made WHILE swaps = TRUE swaps ← FALSE // Loop through array from start to the second-last unsorted element FOR y ← 1 TO numlength - 1 // If current number is greater than the next number, swap IF nums[y] > nums[y + 1] THEN DECLARE temp : INTEGER temp ← nums[y] nums[y] ← nums[y + 1] nums[y + 1] ← temp swaps ← TRUE // A swap was made ENDIF NEXT y // Decrease the range as the last value is now sorted numlength ← numlength - 1 ENDWHILE // Output the sorted array FOR i ← 1 TO 11 OUTPUT nums[i] NEXT i

2D Arrays

  • Type of array where each element is itself an array
  • Can be visualized as a table with rows and columns
  • Ideal for representing grid-like structures such as matrices, game boards or spreadsheets
  • It consists of multiple rows and columns, where each element is uniquely identified by its row and column values.
  • Applications: Images, screens and game boards

Example

A 2D array to store student grades for 4 subjects and 3 students.

Student 1Student 2Student 3
Physics909179
Chemistry805060
Maths826775
Computer Science789295

This can be represented in Python as the following

grades = [ [90, 91, 79], # Grades for Physics [80, 50, 60], # Grades for Chemistry [82, 67, 75], # Grades for Maths [78, 92, 95] # Grades for CS ] # Accessing an element # Array[row][column] print(grades[3][1]) # Output: 92 # Printing the entire 2D array for row in grades: for col in grades: print(grades[row][col])
Pseudocode
// DECLARE <identifier>:ARRAY[<lower1>:<upper1>,<lower2>:<upper2>] OF <data // type> DECLARE NoughtsAndCrosses : ARRAY[1:3,1:3] OF CHAR //ArrayName[row, column] - Accessing Element NoughtsAndCrosses[2,3] ← ꞌXꞌ //Setting value of an element

Subroutine

  • Subroutine is a reusable block of code that is given a name
  • Designed to perform a specific task
  • Often called within a program to avoid repetition.
  • Can be tested/improved independently of program
  • Easy to share procedures/functions with other programs
  • Create routines that can be called like built-in command
  • Header: The first statement in subroutine definition
    • Includes name of the subroutine
    • Includes parameter passed along with data type
    • Includes return data type if it exists

Procedure

  • Subroutine that does not return a value
  • Procedure calls are standalone statements

Function

  • Subroutine that returns a value.
  • Function calls are always made as part of an expression
  • The keyword RETURN is used as one of the statements within the body of the function to specify the value to be returned.
  • Normally, this will be the last statement in the function definition, however, if the RETURN statement is in the body of the function its execution is immediate and any subsequent lines of code are omitted.
  • Because a function returns a value that is used when the function is called, function calls are not complete program statements
  • When the RETURN statement is executed, the value returned replaces the function call in the expression and the expression is then evaluated

Parameter

  • Variables used in a subroutine to accept input values, allowing data to be passed into the subroutine.
  • A subroutine may or may not have parameters.
  • When calling a function, the parameters used must be of correct data type and of the same sequence as the definition
  • Parameters should not be passed by reference to a function.
  • Unless otherwise stated, it should be assumed that parameters are passed by value.
  • Parameters can be passed either by reference or by value (not supported in python)
  • Pass by value: Data copied into procedure so variable not changed outside procedure
  • Pass by reference: Link to variable provided so variable changed after going through procedure

Argument: The actual value or data passed to the subroutine when it is called

Local Variable: Variables defined within a function or block, accessible only within that specific scope. These variables are not accessible outside the subroutine

Global Variable: Variables defined outside all functions or blocks, accessible throughout the entire program.

Procedure/Function Interface: The way a procedure or function interacts with the rest of the program. It includes its name, parameters (inputs), and, for functions, the return value.

# In python function and procedures are defined the same way # Arguments data type is not mentioned def calculate_area(): #Function definition width = int(input("Enter Width: ") height = int(input("Enter Height: ") return width * height calculate_area() #Calling a function def meter_to_feet(meter): #Procedure with argument passed print(meter * 3.28) calculate_area(5) #Prints 5 * 3.28
Pseudocode
A procedure with no parameters is defined as follows: PROCEDURE <identifier>() <statement(s)> ENDPROCEDURE A procedure with parameters is defined as follows: PROCEDURE <identifier>(<param1> : <data type>, <param2> : <data type>...) <statement(s)> ENDPROCEDURE Procedures defined as above should be called as follows, respectively: CALL <identifier>() CALL <identifier>(value1, value2, ...)
A function with no parameters is defined as follows: FUNCTION <identifier>() RETURNS <data type> <statement(s)> ENDFUNCTION A function with parameters is defined as follows: FUNCTION <identifier>(<param1> : <data type>, <param2> : <data type>...) RETURNS <data type> <statement(s)> ENDFUNCTION Example of a function use FUNCTION Max(Number1 : INTEGER, Number2 : INTEGER) RETURNS INTEGER IF Number1 > Number2 THEN RETURN Number1 ELSE RETURN Number2 ENDIF ENDFUNCTION OUTPUT "Penalty Fine = ", Max(10, Distance*2)
To specify whether a parameter is passed by value or by reference, the keywords BYVAL and BYREF precede the parameter in the definition of the procedure. If there are several parameters passed by the same method, the BYVAL or BYREF keyword need not be repeated. Example – passing parameters by reference PROCEDURE SWAP(BYREF X : INTEGER, Y : INTEGER) Temp ← X X ← Y Y ← Temp ENDPROCEDURE

Library Routines

  • A library routine is a pre-written, reusable function or procedure provided by a programming library to perform common tasks, such as mathematical operations or input/output handling.
  • IDEs typically include a standard library of functions and procedures
  • Programming language development systems often offer library routines that can be easily integrated into programs
  • Some examples of library routines in pseudocode are: MOD, DIV, ROUND, RANDOM

Best Coding Practices

  • Use meaningful identifiers name for variables, constants, arrays, procedure, functions
  • Use commenting feature wisely
  • Divide the program into different modules using procedures and functions

String Manipulation

Strings are conceptually like arrays of characters. This means many operations done in arrays can be done in string. In pseudocode, the first character index may be 0 or 1, but for the functions of the insert it is not zero indexed.

# Using quotes inside string print("You're amazing!") a = "String Manipulation" print(a[5]) #Outputs g #Prints every letter in the phrase for x in a: print(x)#Prints every letter of a

Slicing/Substring: Returns a range of characters by specifying a start and end index (exclusive)
Concatenation: Combining two or more strings together

PythonPseudocode
a = "String Manipulation" print(len(a) #Returns 19 print(a[3:8]) #Returns index 3 to 7 print(a[:]) #Returns whole string print(a[:6]) #Returns Start to index 5 print(a[7:]) #Returns index 7 to end print(a[-1]) #Returns last character print(a[-5:-3]) #Returns "ati" print(a.upper()) #Convert to uppercase print(a.lower()) #Convert to lowercase b = "Hello" c = "World" print(a + b) #HelloWorld print(a + " " + b) #Hello World print(str(56)) print(int("-56")) print(float("56.6")) print(a.isnumeric()) #Returns False print(chr(97)) #Integer to ascii print(ord('A')) #Ascii to integera ← "String Manipulation" OUTPUT LENGTH(a) OUTPUT MID(a, 4, 5) OUTPUT a OUTPUT LEFT(a, 6) OUTPUT RIGHT(a, 12) OUTPUT RIGHT(a, 1) OUTPUT MID(a, 15, 3) OUTPUT TO_UPPER(a) OUTPUT TO_LOWER(a) b ← "Hello" c ← "World" OUTPUT b & c OUTPUT b & " " & c OUTPUT NUM_TO_STR(56) OUTPUT STR_TO_NUM("-56") OUTPUT STR_TO_NUM("56.6") OUTPUT IS_NUM(a) OUTPUT CHR(97) OUTPUT ASC('A')

Pseudocode String Functions

The Cambridge International AS & A Level syllabus (9618) specifically requires candidates to know string manipulation functions in their chosen programming language. Pseudocode string manipulation functions
will always be provided in examinations (In Insert). Some basic string manipulation functions are given here.

An error will be generated if a function call is not properly formed or if the parameters are of an incorrect type or an incorrect value.

String and character functions

  • A string of length 1 may be considered to be either of type CHAR or STRING
  • A CHAR may be assigned to, or concatenated with, a STRING
  • A STRING of length greater than 1 cannot be assigned to a CHAR
  • These functions are not zero-indexed
LEFT(ThisString : STRING, x : INTEGER) RETURNS STRING returns leftmost x characters from ThisString
RIGHT(ThisString : STRING, x : INTEGER) RETURNS STRING returns rightmost x characters from ThisString
LENGTH(ThisString : STRING) RETURNS INTEGER returns the integer value representing the length of ThisString
MID(ThisString : STRING, x : INTEGER, y : INTEGER) RETURNS STRING returns a string of length y starting at position x from ThisString
UCASE(ThisChar : CHAR) RETURNS CHAR returns the character value representing the upper-case equivalent of ThisChar
TO_UPPER(ThisString : STRING) RETURNS STRING returns a string formed by converting all characters of ThisString to uppercase
LCASE(ThisChar : CHAR) RETURNS CHAR returns the character value representing the lower-case equivalent of ThisChar
TO_LOWER(ThisString : STRING) RETURNS STRING returns a string formed by converting all characters of ThisString to lowercase
NUM_TO_STR(x : <datatype1>) RETURNS <datatype2> returns a string representation of a numeric value (supports -ve). <datatype1> may be REAL or INTEGER, <datatype2> may be CHAR or STRING
STR_TO_NUM(x : <datatype1>) RETURNS <datatype2> returns a numeric representation of a string. <datatype1> may be CHAR or STRING, <datatype2> may be REAL or INTEGER
IS_NUM(ThisString : <datatype>) RETURNS BOOLEAN returns TRUE if ThisString represents a valid numeric value. <datatype> may be CHAR or STRING
ASC(ThisChar : CHAR) RETURNS INTEGER returns an integer value (the ASCII value) of character ThisChar
CHR(x : INTEGER) RETURNS CHAR returns the character whose integer value (the ASCII value) is x
In pseudocode, the operator & is used to concatenate (join) two strings. Example: “Summer” & “ “ & “Pudding” produces “Summer Pudding”

Where string operations (such as concatenation, searching and splitting) are used in a programming language, these should be explained clearly, as they vary considerably between systems.

Where functions in programming languages are used to format numbers as strings for output, their use should also be explained.

Numeric Functions

PythonPseudocode
import random print(random.random()) print(random.randrange(0, 50)) print(int(1.56))# No import necessary OUTPUT RAND(1) OUTPUT RAND(50) OUTPUT INT(1.56)

Pseudocode Numeric Functions

INT(x : REAL) RETURNS INTEGER returns the integer part of x
RAND(x : INTEGER) RETURNS REAL returns a real number in the range 0 to x (not inclusive of x). Example: RAND(87) could return 35.430729

Date Functions

  • There is not built in data type of date, however we can import a module to make it work
  • Date format pseudocode is assumed to be DD/MM/YYYY unless otherwise stated.
PythonPseudocode
import datetime # Returns current time and date now = datetime.datetime.now() print(now.year) print(now.month) print(now.day) #This is zero index print(now.strftime("%w")) #Sunday = 0 # Creating a date:(year, month, day) d = datetime.datetime(2020, 5, 17)// No import needed // Returns current time and date now ← TODAY() OUTPUT YEAR(now) OUTPUT MONTH(now) OUTPUT DAY(now) // This is one indexed OUTPUT DAYINDEX(now) // Sunday = 1 //Creating a date:(year, month, day) d = datetime.datetime(17, 5, 2020)

Pseudocode Date Functions

DAY(ThisDate : DATE) RETURNS INTEGER returns the day number from ThisDate
MONTH(ThisDate : DATE) RETURNS INTEGER returns the month number from ThisDate
YEAR(ThisDate : DATE) RETURNS INTEGER returns the year number from ThisDate
DAYINDEX(ThisDate : DATE) RETURNS INTEGER returns the day index number from ThisDate where Sunday = 1, Monday = 2 etc.
SETDATE(Day, Month, Year : INTEGER) RETURNS DATE returns a value of type DATE with the value of <Day>/<Month>/<Year>
TODAY() RETURNS DATE returns a value of type DATE corresponding to the current date.

Record Structure

  • Record structure is used to hold a set of different data types under one identifier
  • Python uses object and classes instead of record structure
PythonPseudocode
# Record Declaration class <identifier>: def __init__(self, i1, i2): self.i1 = i1 self.i2 = i2 ……… Example – Declaration of Record data type This user-defined data type holds data about a student. class StudentRecord: def __init__(self, LastName, FirstName, DateOfBirth, YearGroup, FormGroup): self.LastName = LastName self.FirstName = FirstName self.DateOfBirth = DateOfBirth self.YearGroup = YearGroup self.FormGroup = FormGroup Example – using user-defined data types Form = [0] * 30 Pupil1 = StudentRecord() Pupil1.LastName = "Johnson" Pupil1.Firstname = "Leroy" Pupil1.DateOfBirth = 02/01/2005 Pupil1.YearGroup = 6 Pupil1.FormGroup = ꞌAꞌ Pupil2 = Pupil1 for index in range(1, 30): Form[Index].YearGroup ← Form[Index].YearGroup + 1Record Declaration: TYPE <identifier1> DECLARE <identifier2> : <dataType> DECLARE <identifier3> : <dataType> ... ENDTYPE Example – Declaration of Record data type This user-defined data type holds data about a student. TYPE StudentRecord DECLARE LastName : STRING DECLARE FirstName : STRING DECLARE DateOfBirth : DATE DECLARE YearGroup : INTEGER DECLARE FormGroup : CHAR ENDTYPE Example – using user-defined data types DECLARE Pupil1 : StudentRecord DECLARE Pupil2 : StudentRecord DECLARE Form : ARRAY[1:30] OF StudentRecord Pupil1.LastName ← "Johnson" Pupil1.Firstname ← "Leroy" Pupil1.DateOfBirth ← 02/01/2005 Pupil1.YearGroup ← 6 Pupil1.FormGroup ← ꞌAꞌ Pupil2 ← Pupil1 FOR Index ← 1 TO 30 Form[Index].YearGroup ← Form[Index].YearGroup + 1 NEXT Index

File Handling

  • Text files consist of lines of text that are read or written consecutively as strings
  • The purpose of storing data in a file is to be used again by a program
  • Data in files are stored permanently, meaning they can be used later
  • It is good practice to explicitly open a file, stating the mode of operation, before reading from or writing to it.
  • File can be opened in three modes:
    • READ: for data to be read from the file
    • WRITE: for data to be written to the file. A new file will be created and any existing data in the file will be lost
    • APPEND: for data to be added to the file, after any existing data
  • A file should be opened in only one mode at a time
# Opening a file - open(filename, mode) # Modes: r = read, w = write f = open("test_file.txt", "r") print(f.read()) # Reads the full file at once print(f.readline()) # Reads one line from the file print(f.readline()) # Reads the next line from the file for x in f: #Loops through the file print(x) f.close() #Closes the file f = open("test_file2.txt", "w") f.write("Test sentence") #Writes a line in the file f.close()
Pseudocode
Opening a file OPENFILE <File identifier> FOR <File mode> The file identifier will be the name of the file with a data type of string. Data is read from the file (after opening in READ mode) using the following: READFILE <file Identifier>, <variable> When the command is executed, the data item is read and assigned to the variable (the data type is string) To test whether there are any more lines to be read from the file EOF(<file identifier>) This function returns TRUE if there are no more lines to read (or if an empty file has been opened in READ mode) and FALSE otherwise Data is written into the file after opening using the following command: WRITEFILE <file identifier>, <variable> When the command is executed, the data is written into the file. Files should be closed when they are no longer needed. CLOSEFILE <file identifier> //Closes the file This example uses the operations together, to copy all the lines from FileA.txt to FileB.txt**, replacing any blank lines by a line of dashes.** DECLARE LineOfText : STRING OPENFILE "FileA.txt" FOR READ OPENFILE "FileB.txt" FOR WRITE WHILE NOT EOF("FileA.txt") READFILE "FileA.txt", LineOfText IF LineOfText = "" THEN WRITEFILE "FileB.txt", " ----------------------------" ELSE WRITEFILE "FileB.txt", LineOfText ENDIF ENDWHILE CLOSEFILE "FileA.txt" CLOSEFILE "FileB.txt"

Abstract Data Type (ADT)

Defines a data structure by its behavior from the user's perspective, rather than its concrete implementation. ADT is a collection of data and a set of operations on those data.
Examples: Stack, Queue, Linked List

Stack

  • A list operating on the Last In First Out principle (LIFO)
  • Push: Adding item to stack
  • Pop: Removing item from the stack
  • isEmpty: Checks if stack is empty
  • The first item added to the stack is the last item that can be removed
  • Implementing stack using array
    • Declare an array to store the contents of stack
    • Declare a stack pointer pointing to the index of last element added (Value -1 if stack is empty)
  • Uses: Managing function calls, Syntax parsing in compilers, Recursion, 'Undo' functions, System memory architecture, Browsing history, Expression parsing (Reverse Polish Notation)
  • Advantage: Simple, Efficient, Limited Memory, LIFO
  • Disadvantage: Limited access, Random access not possible, Limited capacity leading to overflow

Queue

  • A list operating on the First In First Out principle (FIFO)
  • The first item added is the first item to be removed
  • Data is added from the rear end by using the EndPointer/TailPointer and removed from the front by using the StartPointer/HeadPointer
  • Enqueue: Add an element to the back of the queue.
  • Dequeue: Remove the element at the front of the queue.
  • isEmpty: Check if the queue is empty.
  • Applications: Task Scheduling in OS and printer, Handling request in web server, streaming, call centers, handling packets, messaging or ordering services, video or mp3 players, traffic management, physical queues like supermarket

  • Advantages: Large data managed efficiently, multi user services
  • Disadvantages: Operations on middle elements are hard, maximum size defined before implementation

Linked List

  • Nodes: Basic data structure which contains data and one or more links/pointers to other nodes. Nodes can be used to represent a tree structure or a linked list.
    • Node’s successor is the next node
    • Node's predecessor is the previous node
  • Pointers: Variable that stores the memory address of another variable as its value
  • A linked list is a data structure used to store a collection of items where each item is linked to the next one using pointers.
  • Traverse a linked list: Start at the first node and then go from node to node, following each node’s pointer to find the next node.
  • Two types depending on how data is sorted: ordered and unordered.
  • Linked List can be implemented using 2D Arrays (Singly)
    • The arrays are for data and the other for pointers
  • Advantage: Fast insertion and deletion
  • Disadvantage: Slow Search