Data Types and Structures
Choosing the right container: simple types, records, arrays and files, and the stack, queue and linked list.
Choosing a data type
Pick a data type by what you will do with the value. Each type is written in its own way.
A data type is the kind of value a variable holds. Pseudocode has six basic data types:
| Type | Holds | Written | Example |
|---|---|---|---|
INTEGER | a whole number | as it is | 5, -3 |
REAL | a number that can have a fractional part | always with a digit on each side of the point | 4.7, 0.3, 4.0 |
CHAR | exactly one character | in single quotes | 'x' |
STRING | zero or more characters | in double quotes | "Bat", "" |
BOOLEAN | TRUE or FALSE | as a word | TRUE |
DATE | a date | normally dd/mm/yyyy | 26/10/2009 |
Choose by what you will do with the value.
Example:A student ID such as 00417 is a STRING. You never do arithmetic on it, and an INTEGER would store it as 417.
DECLARE StudentCount : INTEGER // 30 DECLARE AverageMark : REAL // 64.5 DECLARE Grade : CHAR // 'B' DECLARE StudentID : STRING // "00417" DECLARE FeesPaid : BOOLEAN // TRUE DECLARE DateOfBirth : DATE // 26/10/2009
Records: several types under one name
A record keeps several facts about one thing together under one name, even when their types differ.
A record is a data type you define yourself. It holds several fields (named parts) under one identifier. The fields can be of different data types. So one variable can hold everything about one student.
Why not use parallel arrays, one for names and one for years? They can fall out of step. A record keeps the fields together.
How to use a record:
- Define the type with
TYPEandENDTYPE. - Declare variables of that type.
- Reach a field with a dot, as in
Pupil1.FirstName.
One assignment, Pupil2 ← Pupil1, copies a whole record. The copy is separate from the original.
Example:An array can hold records too. After DECLARE Form : ARRAY[1:30] OF StudentRecord, Form[1].FirstName is the first student's first name.
TYPE StudentRecord DECLARE LastName : STRING DECLARE FirstName : STRING DECLARE YearGroup : INTEGER DECLARE FormGroup : CHAR ENDTYPE DECLARE Pupil1 : StudentRecord DECLARE Pupil2 : StudentRecord Pupil1.LastName ← "Erdene" Pupil1.FirstName ← "Bat" Pupil1.YearGroup ← 11 Pupil1.FormGroup ← 'B' Pupil2 ← Pupil1 Pupil2.FirstName ← "Saraa" OUTPUT Pupil1.FirstName, " ", Pupil2.FirstName
One-dimensional arrays
An array is a numbered row of values of one type, like a row of numbered lockers.
An array is a fixed-length structure of elements of the same data type, under one identifier. Think of a row of school lockers, each with a number.
DECLARE Names : ARRAY[1:8] OF STRING has 8 elements, Names[1] to Names[8].
| Word | Meaning | In Names |
|---|---|---|
| index (or subscript) | the number that picks one element | the 3 in Names[3] |
| lower bound | the index of the first element | 1 |
| upper bound | the index of the last element | 8 |
An index outside the bounds is an error.
Exam:Always state the lower bound. Some systems start at 0 and others at 1. 9618 pseudocode usually uses 1.
Watch out:To set every element, use a loop. A statement should not refer to a group of elements, such as Names[1 TO 8].
DECLARE Names : ARRAY[1:8] OF STRING DECLARE Index : INTEGER FOR Index ← 1 TO 8 Names[Index] ← "" NEXT Index
Two-dimensional arrays and nested loops
A 2D array is a table with rows and columns. A loop inside a loop visits every cell.
A 2D array is a table of elements of one data type, like a seating plan of a classroom.
| 1D array | 2D array | |
|---|---|---|
| Shape | one list | a table |
| Declared with | one range | two ranges |
| Reached with | one index | two indexes, as in Marks[2, 3] |
| Use it for | one list | data with two dimensions: marks for several students in several tests, or a game board |
The question says which index is which. The first is usually the row.
Process a 2D array with a loop inside a loop (a nested loop):
- The outer loop picks the row.
- The inner loop visits every column of that row.
Here each mark is input as its cell is reached.
DECLARE Marks : ARRAY[1:4, 1:3] OF INTEGER DECLARE Row : INTEGER DECLARE Column : INTEGER DECLARE RowTotal : INTEGER DECLARE Total : INTEGER Total ← 0 FOR Row ← 1 TO 4 RowTotal ← 0 FOR Column ← 1 TO 3 INPUT Marks[Row, Column] RowTotal ← RowTotal + Marks[Row, Column] NEXT Column OUTPUT "Total for student ", Row, " is ", RowTotal Total ← Total + RowTotal NEXT Row OUTPUT "The grand total is ", Total
Linear search
A linear search checks the items one by one, from the first, until it finds the one it wants.
A linear search checks each element in turn, starting from the first. It stops when it finds the item or reaches the end. It is like reading down a class list to find a friend's name.
The data does not have to be sorted.
How to write it:
- Use a conditional loop, so the search stops as soon as the item is found.
- Use a Boolean flag,
Found, to remember whether it was found. - After the loop, output the position, or "not found".
The code searches the Names array for the name in SearchName.
Remember:When the item is in the last element, or not there at all, every element is checked.
Index ← 1 Found ← FALSE WHILE Found = FALSE AND Index <= 8 IF Names[Index] = SearchName THEN Found ← TRUE ELSE Index ← Index + 1 ENDIF ENDWHILE IF Found = TRUE THEN OUTPUT SearchName, " found at position ", Index ELSE OUTPUT SearchName, " not found" ENDIF
Bubble sort, the efficient version
A bubble sort swaps neighbours that are in the wrong order, pass after pass, until no swaps are needed.
A bubble sort compares each pair of neighbours (elements next to each other). It swaps them if they are in the wrong order.
After one pass (one trip through the list), the largest value has bubbled to the end.
Exam:Mark schemes look for two improvements. Know both.
| Improvement | How it works | Why |
|---|---|---|
Boundary | goes down by one after each pass; here Numbers holds 6 values, so Boundary starts at 5 | the end of the list is already sorted |
NoSwaps | set to TRUE at the start of each pass, and to FALSE by any swap | a pass with no swaps means the list is sorted, so the sort stops |
The nearly sorted preset stops after 2 passes.
Boundary ← 5 REPEAT NoSwaps ← TRUE FOR Index ← 1 TO Boundary IF Numbers[Index] > Numbers[Index + 1] THEN Temp ← Numbers[Index] Numbers[Index] ← Numbers[Index + 1] Numbers[Index + 1] ← Temp NoSwaps ← FALSE ENDIF NEXT Index Boundary ← Boundary - 1 UNTIL NoSwaps = TRUE
Why files are needed
Variables vanish when a program ends. A file keeps the data for next time.
While a program runs, its variables are held in main memory. A file is kept on secondary storage (such as a hard disk), which does not need power to keep its data.
| Variables in main memory | A file on secondary storage | |
|---|---|---|
| When the program ends, or the computer is switched off | the values are lost | the data is still there |
| The next time the program runs | someone must type the data in again | the program reads the data back from the file |
| How much it holds | an array has a fixed size | as many lines as the storage has room for |
Example:A game saves your high score in a file. Tomorrow it reads the score back.
Text files in pseudocode
A text file is read or written one line at a time, after you open it in the right mode.
A text file holds lines of text. You read or write it one line at a time, as strings.
Open a file in one file mode before you use it:
| Mode | What it does |
|---|---|
READ | reads lines |
WRITE | creates a new file; any data already in it is lost |
APPEND | adds lines after the existing data |
The commands:
READFILEreads the next line into aSTRINGvariable.EOF(file)isTRUEwhen there are no more lines to read.WRITEFILEwrites one line.CLOSEFILEcloses the file when it is no longer needed.
Remember:Read to the end with WHILE NOT EOF. The test comes before the first READFILE, so an empty file is never read.
DECLARE Line : STRING OPENFILE "Scores.txt" FOR WRITE WRITEFILE "Scores.txt", "Bat,78" WRITEFILE "Scores.txt", "Saraa,55" CLOSEFILE "Scores.txt" OPENFILE "Scores.txt" FOR APPEND WRITEFILE "Scores.txt", "Tuya,91" CLOSEFILE "Scores.txt" OPENFILE "Scores.txt" FOR READ WHILE NOT EOF("Scores.txt") READFILE "Scores.txt", Line OUTPUT Line ENDWHILE CLOSEFILE "Scores.txt"
Abstract data types, and the stack
A stack is like a pile of plates: you add and remove only at the top. Last in, first out.
An abstract data type (ADT) is a collection of data and a set of operations on those data.
A stack is an ADT that is last in, first out (LIFO). Items are added (PUSH) and removed (POP) only at the top.
Built with an array, it needs the array and a pointer, TopOfStack. It holds the index of the last item added. Here 0 means the stack is empty.
PUSH an item onto Stack[1:8]:
- If
TopOfStack= 8, the stack is full: report overflow. - Otherwise add 1 to
TopOfStack. - Store the item in
Stack[TopOfStack].
POP an item:
- If
TopOfStack= 0, the stack is empty: report underflow. - Otherwise take the item in
Stack[TopOfStack]. - Subtract 1 from
TopOfStack.
A popped value stays in memory. It is simply no longer part of the stack.
Exam:AS does not ask you to write a stack in pseudocode. But you must be able to add and remove its items by hand.
The queue, and the circular queue
A queue is like a line at the canteen: you join at the rear and leave from the front.
A queue is an ADT that is first in, first out (FIFO). Built with an array, it needs a front pointer and a rear pointer. Here a count, Length, makes full and empty easy to test.
Queue[1:6] starts with FrontPointer 1, RearPointer 0 and Length 0.
ENQUEUE (add) an item:
- If
Length= 6, the queue is full: report it. - Otherwise move
RearPointeron one place. - Store the item in
Queue[RearPointer]. - Add 1 to
Length.
DEQUEUE (remove) an item:
- If
Length= 0, the queue is empty: report it. - Otherwise take the item in
Queue[FrontPointer]. - Move
FrontPointeron one place. - Subtract 1 from
Length.
In a circular queue, a pointer that passes the last index goes back to the first. Here, after 6 it goes back to 1. So space freed at the front is used again.
The linked list: data and pointers
In a linked list, each item points to the next one, so you change pointers instead of moving data.
A linked list keeps items in order without moving them. Each node holds data and a pointer to the next node. It is like a treasure hunt: each clue tells you where the next one is.
- A start pointer shows where the list begins.
- A null pointer marks the end.
Built with arrays, it needs a data array, a pointer array, a start pointer and a free-list pointer to the first unused node. The unused nodes form their own list, the free list.
Add an item:
- Check that there is a free node:
FreeListPointeris not null. - Put the data in node
FreeListPointer. - Move
FreeListPointeron to the next free node. - Follow the pointers from
StartPointerto find where the item belongs. - Change two pointers: point the new node at the node after it, and point the node before it (or
StartPointer) at the new node.
Delete an item:
- Follow the pointers to the node, remembering the node before it.
- Point the node before it (or
StartPointer) past it. - Give the node back to the free list.
Choosing a structure for a task
Choose a data structure by the feature the task needs, and say that feature in your answer.
| Structure | Its feature | A task that needs it |
|---|---|---|
| Array | a fixed number of items of one type, reached by position | marks for 30 students; in 2D, a timetable or a game board |
| Record | items of different types about one thing | one student |
| Stack | last in, first out | undo in an editor: the last change is undone first |
| Queue | first in, first out | print jobs, printed in the order they arrive |
| Linked list | items kept in order; only pointers change, and no data moves | items often added and removed in the middle |
Exam:Justify a structure by the feature the task needs. Do not just name it.
RUN THE PSEUDOCODE
Write the pseudocode your syllabus uses and press Run. Assignment is the arrow — type <- and it works the same as ←. Both syllabuses are accepted, so OUTPUT and PRINT both work; where a word differs from the one the exam prints, the runner says so.
Press Run to see what it doesTotal ← 0
FOR Count ← 1 TO N
Total ← Total + Count
NEXT Count
OUTPUT TotalSTARTN = 5
| Count | Total | OUTPUT |
|---|---|---|
One row per pass through the loop. Leave a cell blank if it does not change on that pass.
KEY TERMS
CHECK YOURSELF
1.Why use a record rather than several parallel arrays?
2.Scores.txt already holds two lines. A program opens it FOR WRITE and writes one line. How many lines does the file hold now?
3.Print jobs must be printed in the order they arrive. Which structure should hold them?
4.A bubble sort puts an array into ascending order. After one full pass, what is certain?
5.Which of these is a valid REAL literal in 9618 pseudocode?
6.A new name is added to a linked list that is held in arrays. What happens to the names already in it?