1. Basic Control Structures
1.1Input and Output Statements
Basic pseudocode for user input and displaying output.
INPUT StudentName OUTPUT "You have made an error" OUTPUT StudentName OUTPUT "Student name is ", StudentName
1.2Assignment Statements
Variable assignment with arithmetic and string operations.
Counter <- 1 Counter <- Counter + 1 MyChar <- "A" LetterValue <- ASC(MyChar) StudentMark <- 40 Percentage <- (StudentMark / 80) * 100 OldString <- "Your mark is" NewString <- OldString & " ninety-seven"
1.3IF Statement - Single Choice
Simple conditional selection with IF-THEN-END IF.
IF MyValue > YourValue THEN OUTPUT "I win" END IF
1.4IF Statement - With Alternative
Conditional selection with IF-THEN-ELSE-END IF.
IF MyValue > YourValue THEN OUTPUT "I win" ELSE OUTPUT "You win" END IF
1.5CASE Statement - Multiple Choices
Multiple selection using CASE with direction example.
CASE OF Direction "N": Y <- Y + 1 "S": Y <- Y - 1 "E": X <- X + 1 "W": X <- X - 1 END CASE
1.6CASE Statement - With Otherwise
CASE statement with error handling using OTHERWISE.
CASE OF Direction "N": Y <- Y + 1 "S": Y <- Y - 1 "E": X <- X + 1 "W": X <- X - 1 OTHERWISE : OUTPUT "Error" END CASE
1.7FOR Loop - Fixed Iterations
Count-controlled loop with FOR-TO-NEXT.
Total <- 0 FOR Counter <- 1 TO 10 OUTPUT "Enter a number " INPUT Number Total <- Total + Number NEXT Counter OUTPUT "The total is ", Total
1.8FOR Loop - With STEP
FOR loop counting in increments using STEP.
FOR Counter <- 1 TO 10 STEP 2 OUTPUT Counter NEXT Counter
1.9REPEAT-UNTIL Loop
Post-condition loop that executes at least once.
REPEAT OUTPUT "Please enter a positive number " INPUT Number UNTIL Number > 0
1.10WHILE Loop
Pre-condition loop that may not execute at all.
Number <- 0 WHILE Number >= 0 DO OUTPUT "Please enter a negative number " INPUT Number END WHILE
2. Validation Algorithms
2.1Validate Positive Number Less Than Fifty
Input validation using REPEAT-UNTIL with compound condition.
REPEAT OUTPUT "Please enter a positive number less than fifty" INPUT Number UNTIL (Number > 0) AND (Number < 50)
2.2Validate Integer Input
Ensuring input is a positive whole number using INT function.
REPEAT OUTPUT "Enter the number of values to average" INPUT Number UNTIL (Number > 0) AND (Number = INT(Number))
2.3Validate Integer Value
Validating that input value is an integer.
REPEAT OUTPUT "Enter an integer value " INPUT Value UNTIL Value = INT(Value)
2.4Calculate Average with Validation
Complete algorithm to calculate average with input validation.
Total <- 0 REPEAT PRINT "Enter the number of values to average" INPUT Number UNTIL (Number > 0) AND (Number = INT(Number)) FOR Counter <- 1 TO Number REPEAT PRINT "Enter an integer value " INPUT Value UNTIL Value = INT(Value) Total <- Total + Value NEXT Counter Average <- Total / Number PRINT "The average of ", Number, " values is ", Average
3. Array Operations
3.11D Array Declaration
Declaring a one-dimensional array with lower and upper bounds.
DECLARE myList : ARRAY[0:8] OF INTEGER myList[7] <- 16
3.22D Array Declaration
Declaring a two-dimensional array (table with rows and columns).
DECLARE myArray : ARRAY[0:8,0:2] OF INTEGER myArray[7,0] <- 16
3.3Populate 1D Array with FOR Loop
Using FOR loop to fill a one-dimensional array.
DECLARE myList : ARRAY[0:8] OF INTEGER FOR index <- 0 TO 8 OUTPUT "Enter value for element ", index INPUT myList[index] NEXT index
3.4Populate 2D Array with Nested FOR Loop
Using nested FOR loops to fill a two-dimensional array.
DECLARE myArray : ARRAY[0:8,0:2] OF INTEGER FOR row <- 0 TO 8 FOR col <- 0 TO 2 OUTPUT "Enter value for [", row, ",", col, "]" INPUT myArray[row,col] NEXT col NEXT row
3.5Linear Search Algorithm
Searching for an item in a 1D array using REPEAT-UNTIL.
DECLARE myList : ARRAY[0:8] OF INTEGER DECLARE upperBound : INTEGER DECLARE lowerBound : INTEGER DECLARE index : INTEGER DECLARE item : INTEGER DECLARE found : BOOLEAN upperBound <- 8 lowerBound <- 0 OUTPUT "Please enter item to be found" INPUT item found <- FALSE index <- lowerBound REPEAT IF item = myList[index] THEN found <- TRUE END IF index <- index + 1 UNTIL (found = TRUE) OR (index > upperBound) IF found THEN OUTPUT "Item found" ELSE OUTPUT "Item not found" END IF
3.6Linear Search with Index Output
Extended linear search showing position where item was found.
DECLARE myList : ARRAY[0:8] OF INTEGER DECLARE upperBound : INTEGER DECLARE lowerBound : INTEGER DECLARE index : INTEGER DECLARE item : INTEGER DECLARE found : BOOLEAN DECLARE position : INTEGER upperBound <- 8 lowerBound <- 0 OUTPUT "Please enter item to be found" INPUT item found <- FALSE index <- lowerBound position <- -1 REPEAT IF item = myList[index] THEN found <- TRUE position <- index END IF index <- index + 1 UNTIL (found = TRUE) OR (index > upperBound) IF found THEN OUTPUT "Item found at position ", position ELSE OUTPUT "Item not found" END IF
3.7Bubble Sort Algorithm
Sorting a 1D array using bubble sort with efficiency improvement.
DECLARE myList : ARRAY[0:8] OF INTEGER DECLARE upperBound : INTEGER DECLARE lowerBound : INTEGER DECLARE index : INTEGER DECLARE swap : BOOLEAN DECLARE temp : INTEGER DECLARE top : INTEGER upperBound <- 8 lowerBound <- 0 top <- upperBound REPEAT swap <- FALSE FOR index = lowerBound TO top - 1 IF myList[index] > myList[index + 1] THEN temp <- myList[index] myList[index] <- myList[index + 1] myList[index + 1] <- temp swap <- TRUE END IF NEXT index top <- top - 1 UNTIL (NOT swap) OR (top = 0)
4. File Operations
4.1File Handling Statements Overview
Summary of file operations: OPENFILE, READFILE, WRITEFILE, EOF.
// Open file for reading OPENFILE "filename" FOR READ // Open file for writing (overwrites existing data) OPENFILE "filename" FOR WRITE // Open file for appending (adds to end) OPENFILE "filename" FOR APPEND // Read a line from file READFILE "filename", variable // Write a line to file WRITEFILE "filename", variable // Check for end of file EOF("filename") // Returns TRUE or FALSE
4.2Read Entire Text File
Reading all lines from a text file using EOF function.
OPENFILE "in.txt" FOR READ WHILE NOT EOF("in.txt") READFILE "in.txt", textLine OUTPUT textLine END WHILE CLOSEFILE "in.txt"
4.3Write to Text File
Writing data to a text file line by line.
OPENFILE "out.txt" FOR WRITE FOR count <- 1 TO 100 line <- CONVERT_TO_STRING(count) WRITEFILE "out.txt", line NEXT count CLOSEFILE "out.txt"
4.4Append to Text File
Adding data to the end of an existing file.
OPENFILE "log.txt" FOR APPEND WRITEFILE "log.txt", newData CLOSEFILE "log.txt"
5. Abstract Data Types - Stacks, Queues, Linked Lists
5.1Stack - Setup
Initializing a stack with array and stack pointer.
DECLARE stack : ARRAY[1:10] OF INTEGER DECLARE stackPointer : INTEGER DECLARE maxStack : INTEGER maxStack <- 10 stackPointer <- 0 // stack empty
5.2Stack - Push Operation
Adding an item to the top of the stack with overflow check.
IF stackPointer < maxStack THEN stackPointer <- stackPointer + 1 stack[stackPointer] <- item ELSE OUTPUT "Stack is full, cannot push" END IF
5.3Stack - Pop Operation
Removing an item from the top of the stack with underflow check.
IF stackPointer = 0 THEN OUTPUT "Stack is empty, cannot pop" ELSE item <- stack[stackPointer] stackPointer <- stackPointer - 1 END IF
5.4Queue - Setup (Circular Queue)
Initializing a circular queue with front and rear pointers.
DECLARE queue : ARRAY[1:10] OF INTEGER DECLARE rearPointer : INTEGER DECLARE frontPointer : INTEGER DECLARE queueful : INTEGER DECLARE queueLength : INTEGER DECLARE upperBound : INTEGER frontPointer <- 1 rearPointer <- 0 upperBound <- 10 queueful <- 10 queueLength <- 0
5.5Queue - Enqueue Operation
Adding an item to the rear of a circular queue.
IF queueLength < queueful THEN IF rearPointer < upperBound THEN rearPointer <- rearPointer + 1 ELSE rearPointer <- 1 END IF queueLength <- queueLength + 1 queue[rearPointer] <- item ELSE OUTPUT "Queue is full, cannot enqueue" END IF
5.6Queue - Dequeue Operation
Removing an item from the front of a circular queue.
IF queueLength = 0 THEN OUTPUT "Queue is empty, cannot dequeue" ELSE item <- queue[frontPointer] IF frontPointer = upperBound THEN frontPointer <- 1 ELSE frontPointer <- frontPointer + 1 END IF queueLength <- queueLength - 1 END IF
5.7Linked List - Setup
Initializing a linked list using two parallel arrays and heap management.
DECLARE myLinkedList : ARRAY[0:11] OF INTEGER DECLARE myLinkedListPointers : ARRAY[0:11] OF INTEGER DECLARE startPointer : INTEGER DECLARE heapStartPointer : INTEGER DECLARE index : INTEGER heapStartPointer <- 0 startPointer <- -1 // list empty FOR index <- 0 TO 11 myLinkedListPointers[index] <- index + 1 NEXT index // the linked list heap is a linked list of all the spaces in the linked list // this is set up when the linked list is initialised myLinkedListPointers[11] <- -1 // the final heap pointer is set to -1 to show no further links
6. Text Files with Records
6.1Define Record Type for File Storage
Creating a TYPE definition for records to be stored in a text file.
TYPE TstudentRecord DECLARE name : STRING DECLARE address : STRING DECLARE className : STRING END TYPE
6.2Set Up Text File for Records
Creating and initializing a text file to store records.
// Define the record type TYPE TstudentRecord DECLARE name : STRING DECLARE address : STRING DECLARE className : STRING END TYPE // Create empty file OPENFILE "students.txt" FOR WRITE CLOSEFILE "students.txt"
6.3Append a Record to Text File
Adding a new record to the end of a text file.
TYPE TstudentRecord DECLARE name : STRING DECLARE address : STRING DECLARE className : STRING END TYPE DECLARE student : TstudentRecord DECLARE recordLine : STRING // Get student data OUTPUT "Enter name: " INPUT student.name OUTPUT "Enter address: " INPUT student.address OUTPUT "Enter class: " INPUT student.className // Combine into single string with separator recordLine <- student.name & "," & student.address & "," & student.className // Append to file OPENFILE "students.txt" FOR APPEND WRITEFILE "students.txt", recordLine CLOSEFILE "students.txt"
6.4Find and Delete a Record
Searching for a record and removing it from a text file.
TYPE TstudentRecord DECLARE name : STRING DECLARE address : STRING DECLARE className : STRING END TYPE DECLARE student : TstudentRecord DECLARE recordLine : STRING DECLARE searchName : STRING DECLARE found : BOOLEAN OUTPUT "Enter name to delete: " INPUT searchName found <- FALSE // Read all records OPENFILE "students.txt" FOR READ OPENFILE "temp.txt" FOR WRITE WHILE NOT EOF("students.txt") READFILE "students.txt", recordLine // Extract name (before first comma) commaPos <- 1 WHILE MID(recordLine, commaPos, 1) <> "," commaPos <- commaPos + 1 END WHILE currentName <- LEFT(recordLine, commaPos - 1) IF currentName = searchName THEN found <- TRUE OUTPUT "Record deleted" ELSE WRITEFILE "temp.txt", recordLine END IF END WHILE CLOSEFILE "students.txt" CLOSEFILE "temp.txt" // Replace original with temp file
6.5Output All Records
Displaying all records stored in a text file.
TYPE TstudentRecord
DECLARE name : STRING
DECLARE address : STRING
DECLARE className : STRING
END TYPE
DECLARE student : TstudentRecord
DECLARE recordLine : STRING
OPENFILE "students.txt" FOR READ
WHILE NOT EOF("students.txt")
READFILE "students.txt", recordLine
// Parse the CSV line
commaPos1 <- 1
WHILE MID(recordLine, commaPos1, 1) <> ","
commaPos1 <- commaPos1 + 1
END WHILE
student.name <- LEFT(recordLine, commaPos1 - 1)
remaining <- RIGHT(recordLine, LENGTH(recordLine) - commaPos1)
commaPos2 <- 1
WHILE MID(remaining, commaPos2, 1) <> ","
commaPos2 <- commaPos2 + 1
END WHILE
student.address <- LEFT(remaining, commaPos2 - 1)
student.className <- RIGHT(remaining, LENGTH(remaining) - commaPos2)
OUTPUT "Name: ", student.name
OUTPUT "Address: ", student.address
OUTPUT "Class: ", student.className
OUTPUT "-------------------"
END WHILE
CLOSEFILE "students.txt"
7. Procedures and Functions
7.1Procedure Without Parameters
Defining and calling a simple procedure.
PROCEDURE stars() FOR counter <- 1 TO 10 OUTPUT "*" NEXT counter END PROCEDURE // Call the procedure CALL stars()
7.2Procedure With Parameters (BYVALUE)
Procedure accepting parameters passed by value.
PROCEDURE stars(BYVALUE number : INTEGER) FOR counter <- 1 TO number OUTPUT "*" NEXT counter END PROCEDURE // Call the procedure CALL stars(20)
7.3Procedure With Parameters (BYREF)
Procedure using pass by reference to modify caller's variable.
PROCEDURE celsius(BYREF temperature : REAL) temperature <- (temperature - 32) / 1.8 END PROCEDURE // Usage DECLARE myTemp : REAL myTemp <- 100 CALL celsius(myTemp) OUTPUT myTemp // Now contains Celsius value
7.4Function Without Parameters
Defining a function that returns a value without taking parameters.
FUNCTION getPi() RETURNS REAL RETURN 3.142 END FUNCTION // Usage DECLARE piValue : REAL piValue <- getPi()
7.5Function With Parameters
Function accepting parameters and returning a calculated value.
FUNCTION celsius(temperature : REAL) RETURNS REAL RETURN (temperature - 32) / 1.8 END FUNCTION // Usage DECLARE myTemp : REAL myTemp <- celsius(100) OUTPUT myTemp
7.6Function With String Operations
Function using built-in string functions with error handling.
FUNCTION substring(myString : STRING, start : INTEGER, length : INTEGER) RETURNS STRING IF LENGTH(myString) >= length + start THEN RETURN MID(myString, start, length) ELSE RETURN "" END IF END FUNCTION // Usage DECLARE result : STRING result <- substring("Hello World", 7, 5) OUTPUT result // Displays "World"
7.7Complete Menu-Driven Program
Example of a complete program with menu using procedures and functions.
DECLARE height : REAL DECLARE width : REAL DECLARE maxHeight : INTEGER DECLARE maxWidth : INTEGER DECLARE hypotenuse : REAL DECLARE area : REAL DECLARE choice : INTEGER CONSTANT maxHeightLimit <- 25 CONSTANT maxWidthLimit <- 30 CONSTANT pi <- 3.142 PROCEDURE inputAndValidate() OUTPUT "Enter height: " INPUT height WHILE (height <= 0) OR (height >= maxHeightLimit) DO OUTPUT "Height must be positive and less than ", maxHeightLimit INPUT height END WHILE OUTPUT "Enter width: " INPUT width WHILE (width <= 0) OR (width >= maxWidthLimit) DO OUTPUT "Width must be positive and less than ", maxWidthLimit INPUT width END WHILE END PROCEDURE FUNCTION calculateHypotenuse(h : REAL, w : REAL) RETURNS REAL RETURN SQUAREROOT((h * h) + (w * w)) END FUNCTION FUNCTION calculateArea(h : REAL, w : REAL) RETURNS REAL RETURN (h * w) / 2 END FUNCTION // Main program with menu REPEAT OUTPUT "1. Calculate Hypotenuse" OUTPUT "2. Calculate Area" OUTPUT "3. Exit" OUTPUT "Enter choice: " INPUT choice CASE OF choice 1: CALL inputAndValidate() hypotenuse <- calculateHypotenuse(height, width) OUTPUT "Hypotenuse = ", hypotenuse 2: CALL inputAndValidate() area <- calculateArea(height, width) OUTPUT "Area = ", area 3: OUTPUT "Goodbye" OTHERWISE: OUTPUT "Invalid choice" END CASE UNTIL choice = 3
8. Bubble Sort Optimization
8.1Standard Bubble Sort (Inefficient)
Basic bubble sort with unnecessary comparisons (exam question).
FOR ThisPointer <- 1 TO 9 FOR Pointer <- 1 TO 9 IF NameList[Pointer] > NameList[Pointer + 1] THEN Temp <- NameList[Pointer] NameList[Pointer] <- NameList[Pointer + 1] NameList[Pointer + 1] <- Temp END IF NEXT NEXT
8.2Optimized Bubble Sort
Improved version reducing unnecessary comparisons.
DECLARE NameList : ARRAY[1:10] OF STRING DECLARE Temp : STRING DECLARE ThisPointer : INTEGER DECLARE Pointer : INTEGER DECLARE Top : INTEGER Top <- 10 FOR ThisPointer <- 1 TO 9 FOR Pointer <- 1 TO Top - 1 IF NameList[Pointer] > NameList[Pointer + 1] THEN Temp <- NameList[Pointer] NameList[Pointer] <- NameList[Pointer + 1] NameList[Pointer + 1] <- Temp END IF NEXT Pointer Top <- Top - 1 NEXT ThisPointer
9. Queue as Linked List
9.1Queue Linked List Node Declaration
TYPE definition for a queue node implemented as a linked list.
TYPE Node DECLARE Name : STRING DECLARE Pointer : INTEGER END TYPE DECLARE Queue : ARRAY[1:10] OF Node
9.2Queue AddName Procedure (Linked List)
Adding a name to a queue implemented as a linked list.
PROCEDURE AddName(BYVALUE NewName : STRING) // Report error if no free nodes remaining IF FreePointer = 0 THEN OUTPUT "Error - Queue is full" ELSE // New name placed in node at head of free list CurrentPointer <- FreePointer Queue[CurrentPointer].Name <- NewName // Adjust free pointer FreePointer <- Queue[CurrentPointer].Pointer // If first name in queue then adjust head pointer IF HeadPointer = 0 THEN HeadPointer <- CurrentPointer END IF // Current node is new end of queue Queue[CurrentPointer].Pointer <- 0 TailPointer <- CurrentPointer END IF END PROCEDURE
9.3Queue RemoveName Procedure (Linked List)
Removing a name from a queue implemented as a linked list.
PROCEDURE RemoveName() // Report error if Queue is empty IF HeadPointer = 0 THEN OUTPUT "Error - Queue is empty" ELSE OUTPUT Queue[HeadPointer].Name // Save current head CurrentPointer <- HeadPointer // Update head pointer to next node HeadPointer <- Queue[CurrentPointer].Pointer // If only one element in queue then update tail pointer IF HeadPointer = 0 THEN TailPointer <- 0 END IF // Link released node back to free list Queue[CurrentPointer].Pointer <- FreePointer FreePointer <- CurrentPointer END IF END PROCEDURE