2.2.3

Additional programming techniques

GCSE Computer Science 2.2.3: string manipulation, file handling, records, SQL, one- and two-dimensional arrays, sub programs with local and global variables, and random number generation.

About 26 minutes to read

String manipulation

The specification names two operations specifically: concatenation and slicing.

Concatenation joins strings together, using +. So "Good" + " " + "morning" gives "Good morning". Note the deliberate space — joining "Good" and "morning" directly would give "Goodmorning", which is the commonest slip in this topic.

Slicing takes part of a string out. In Exam Reference Language the main forms are:

• name.length — how many characters the string contains • name.substring(start, number) — a section, starting at a position and taking a number of characters • name.left(n) and name.right(n) — the first or last n characters • name.upper and name.lower — the whole string in upper or lower case

Positions are counted from 0, not 1. So in "COMPUTER", position 0 holds C, and substring(2, 3) gives "MPU" — three characters starting at position 2.

Worked example

A school makes usernames from the first three letters of the surname followed by the first letter of the first name, all in lower case. Write the code for surname = "PATEL" and firstName = "Rachel".

  1. Take the first three characters of the surname, which is a left slice of length 3.
  2. Take the first character of the first name, which is a left slice of length 1.
  3. Concatenate the two results in that order.
  4. Convert the whole thing to lower case at the end, so both parts are covered by one operation.
  5. Check the result by hand before writing it down.

Answer: username = (surname.left(3) + firstName.left(1)).lower surname.left(3) gives "PAT", firstName.left(1) gives "R", concatenation gives "PATR", and .lower gives "patr".

Concatenation
joining strings together using +
Slicing
taking part of a string by specifying a start and end position

File handling

Data held in variables disappears when the program ends. Writing it to a file makes it persistent, so it is still there the next time the program runs.

The specification names four operations, and they happen in a fixed order: open, then read or write, then close.

• myFile = open("scores.txt") — opens the file and gives it a name in the program • myFile.readLine() — reads the next line • myFile.writeLine("text") — writes a line • myFile.close() — closes the file

Closing matters. Until the file is closed, written data may still be sitting in a buffer rather than saved to disk, and the file may stay locked against other programs. Forgetting to close is a real fault, not a formality.

To read a whole file, loop until the end is reached: while NOT myFile.endOfFile() ... endwhile.

Records, arrays and SQL

An array is a fixed-length structure holding a number of items of the same data type under one name, each reached by its index. Being fixed length or static is part of the definition here: the size is set when the array is declared and does not grow.

A one-dimensional array is a single list: scores[0], scores[1], and so on. A two-dimensional array has rows and columns, written as grid[row, column] — used for a game board, a timetable, or, as the specification puts it, to emulate database tables of a collection of fields and records.

A record stores several related items that may be of different data types under one name — a pupil's name as a string, age as an integer and whether they are enrolled as a Boolean. That is the difference to state in an exam: an array holds many items of the same type, a record holds related items of different types.

Figure: A 2D array used as a table of records
pupils[1, 2] holds 65 — row 1, column 2. Rows are the records; columns are the fields.

Processing a 2D array needs nested iteration: an outer loop over the rows and an inner loop over the columns of each row.

SQL is the language for searching data in a database. Three commands are required:

• SELECT — which fields to return, or * for all of them • FROM — which table to take them from • WHERE — the condition a record must meet to be included

So SELECT name, score FROM pupils WHERE score > 70 returns the name and score of every pupil scoring above 70. Note that SELECT * FROM pupils returns every field of every record, since there is no WHERE to filter them.

Array
a fixed-length structure holding a number of items of the same data type under one name, each reached by its index
Record
a structure holding related items of different data types together under one name
SQL
Structured Query Language, used to search for and retrieve data held in a database

Sub programs, scope and random numbers

A sub program is a named block of code that can be called from elsewhere. There are two kinds, and the difference is examined directly:

• A function returns a value to the point it was called from • A procedure carries out a task but returns nothing

So a calculation whose result is needed — working out a total, converting a temperature — belongs in a function. An action that simply happens — printing a menu, saving a file — belongs in a procedure.

Using sub programs produces structured code, and the benefits are worth being able to state: the program is broken into manageable pieces, each can be tested on its own, code written once can be reused many times instead of repeated, and different people can work on different sub programs at the same time.

Figure: Local and global variables
The general rule is to use local variables wherever possible, and pass values in as parameters rather than relying on globals.

Arrays can be passed into a sub program and returned from it, in the same way as any other value.

Random number generation produces an unpredictable value within a range, written as random(1, 6) for a die roll. It is what makes a game different each time it is played, and it is also used for shuffling, for sampling and for generating test data.

Worked example

Write a function that takes an array of marks and returns the average, then call it.

  1. A value is being returned, so this must be a function rather than a procedure.
  2. Take the array as a parameter so the function does not depend on a global variable.
  3. Declare the total inside the function, making it local — nothing outside needs it.
  4. Loop through every element with a count-controlled loop, adding each to the total.
  5. Divide by the number of elements and return the result.

Answer: function average(marks) total = 0 for i = 0 to marks.length − 1 total = total + marks[i] next i return total / marks.length endfunction print(average(classScores))

Common mistake

A procedure does not return a value, so print(myProcedure()) has nothing to print. If a result is needed back, it has to be a function.

Sub program
a named block of code that can be called from elsewhere; a function returns a value, a procedure carries out a task but returns nothing
Scope
the part of a program in which a variable can be accessed; a local variable exists only inside its sub program, a global variable throughout the program

Before you practise

  • Concatenation joins strings with +; remember the space between words.
  • Slicing uses .length, .substring(start, number), .left(n), .right(n), .upper and .lower, counting positions from 0.
  • File handling order: open, read or write, close — and closing is what saves the data.
  • An array is fixed length and holds items of one data type; a record holds related items of different types.
  • A 2D array is addressed as array[row, column] and processed with nested loops.
  • SQL: SELECT the fields, FROM the table, WHERE the condition.
  • A function returns a value; a procedure does not.
  • Sub programs make code testable, reusable and shareable between people.
  • Local variables exist only inside their sub program; globals exist throughout and are riskier.
  • random(1, 6) returns an unpredictable value in that range.

Now practise it

Reading is the easy half. Answer questions on 2.2.3 Additional programming techniques and find out which parts you actually know.