Skip to topic
    ← Back to course topics

    Additional programming techniques — OCR GCSE Computer Science

    Teaching note checked against the official specification.

    Test yourself on Additional programming techniques with OCR GCSE practice questions.

    Start free

    A week of Premium from your first lesson · Then the free plan continues · No card, no charge

    Additional programming techniques explained

    Additional programming techniques covers 7 specification points, including The use of basic string manipulation and The use of basic file handling operations Open….

    Read the full explanation

    Open a point below for its explanation and revision guidance.

    The use of basic string manipulation

    Strings are sequences of characters, and basic string manipulation means extracting, combining, measuring and altering text. Common operations include finding length with len("Hello") giving 5, joining strings with concatenation such as "Hello" + " " + "World", extracting a substring by slicing, for example "Computer"[0:3] giving "Com", and converting case with upper() or lower(). You can also search for a character or substring using find() or in, replace text with replace(), and split a string into parts. Indexing usually starts at 0, so the first character is at position 0. These techniques are used to validate input, format output, search records and process user responses. When manipulating strings, remember that they are immutable: operations return a new string rather than changing the original.

    The use of basic file handling operations Open Read Write Close

    File handling lets a program keep data after it stops running. You open a file to create a connection and choose a mode: read ('r') to fetch existing data, write ('w') to replace or create content, or append ('a') to add to the end. Reading typically uses read(), readline() or readlines() to bring text into a variable. Writing uses write() to send a string to the file. Close() releases the file and flushes buffered data; failing to close can lose data or lock the file. For example, open('scores.txt','w'), write('12\n'), then close() saves one score. Later, open('scores.txt','r'), read the line, convert with int(), and close(). Always match the mode to the task and handle missing files so the program does not crash.

    The use of records to store data

    A record groups related data items about one entity into a single structure. Each field has a name and a data type, such as a student record with fields name (string), age (integer) and average (real). In Python you can implement a record as a dictionary with named keys, for example student = {'name':'Ama','age':14,'average':67.5}. Access a field with student['name'] and update it with student['age'] = 15. Records make programs clearer because fields are referenced by name rather than by position, and they keep related values together. You can store many records in a list or file, then loop through them to search, calculate or display. When reading records from a file, split each line into fields and convert numeric fields before use.

    The use of SQL to search for data

    SQL (Structured Query Language) searches relational databases. OCR J277 requires the commands SELECT, FROM and WHERE. SELECT names the fields to return, FROM names the table, and WHERE filters rows. For example, `SELECT Name FROM Stock WHERE Price < 10` returns the Name value only for records whose Price is below 10. Text values are enclosed in single quotes, for example `WHERE Town = 'Norwich'`. Conditions may be combined with AND when both must be true or OR when either may be true. Candidates must interpret given queries, predict their exact output, and write syntactically correct statements in the order SELECT, FROM, WHERE.

    The use of arrays (or equivalent) when solving problems, including both one-dimensional (1D) and two-dimensional arrays (2D)

    An array stores several values of the same data type under one identifier, each reached by an index. A 1D array is a single list, such as scores[0] to scores[4] holding five test marks. A 2D array is a table of rows and columns, such as grid[2][3], where the first index selects the row and the second the column. You use arrays to avoid many separate variables, to loop through data with a counter, and to store grids for games or tables of records. You must be able to declare an array, assign and read elements, traverse it with a for loop, and process every element, for example totalling a 1D array or searching a 2D array row by row.

    How to use sub programs (functions and procedures) to produce structured code

    Sub programs break a program into named, self-contained blocks that can be called whenever needed. A procedure performs an action and may display or update data without returning a value; a function performs a calculation and returns a value to the caller. Parameters pass data in, and arguments are the actual values supplied. Using sub programs produces structured code: each block has one clear job, so programs are easier to read, test, debug and reuse. For example, a function areaCircle(radius) can return 3.142 × radius², while a procedure displayMenu() can print options. Calling these blocks avoids duplicating code and lets one change fix every use.

    Random number generation

    Random number generation produces values that are not predictable in advance within a chosen range, useful for games, simulations, sampling and testing. Most languages provide a library routine, so the complex generation algorithm need not be written from scratch. These routines are usually pseudorandom: values look random but are produced by a deterministic algorithm, so they are predictable if the seed and algorithm are known. Syntax and bounds are language-specific. In OCR Reference Language, `random(x, y)` returns an integer from x to y inclusive, so a die roll is `random(1, 6)`. In Python, after `import random`, `random.randint(1, 6)` returns an integer from 1 to 6 inclusive. Generated values can be stored in variables, tested with selection, used to index an array, or repeated inside loops.

    Your focus

    1. Apply length, concatenation, slicing, case conversion, search and replace operations to strings.
    2. Trace the output of short string manipulation code, including 0-based indexing.
    3. Explain why strings are immutable and how to create modified strings safely.
    Show all 21 objectives
    1. Open a named text file in a suitable mode for reading, writing or appending.
    2. Read data from a file using read(), readline() or readlines() and store it in variables.
    3. Write or append string data to a file and close it so changes are saved.
    4. Define a record with named fields and appropriate data types for a given scenario.
    5. Create, access and update fields in a record using a dictionary or class attributes.
    6. Store multiple records in a list and process them with iteration.
    7. Write a SELECT query that returns named columns from a stated table.
    8. Apply WHERE conditions, including AND and OR, to filter rows correctly.
    9. Predict the exact output of a given SQL query, including chosen columns.
    10. Declare and use 1D and 2D arrays with correct indices and bounds.
    11. Traverse arrays using loops to read, update and process every element.
    12. Select an appropriate array structure and algorithm to solve a stated problem.
    13. Define a sub program and identify examples of functions and procedures in given code.
    14. Write a function that accepts parameters and returns a value, and a procedure that performs a task.
    15. Explain how using sub programs improves the structure, readability and maintainability of a program.
    16. Describe how a random number generator produces values within a specified range.
    17. Write algorithms that generate a random value and use it in a selection or loop.
    18. Apply random number generation to simulate real-world events like rolling a die.

    Additional programming techniques flashcards

    Card 1 of 10

    Open

    Additional programming techniques exam tips

    Marking Points
    • Uses len() to find the number of characters in a string, e.g. len("OCR") returns 3.
    • Joins strings using concatenation, e.g. forename + " " + surname, and explains that both operands must be strings.
    • Extracts part of a string using slicing or substring, e.g. "Computer"[0:3] returns "Com".
    • Converts case using upper() or lower(), e.g. "Yes".lower() returns "yes".
    • Searches within a string using find() or in, e.g. "cat" in "catalogue" returns True.
    • Replaces characters or substrings using replace(), e.g. "2024".replace("4", "5") returns "2025".
    • Explains that string indexing commonly starts at 0 and that strings are immutable.
    • Opening a file creates a connection between the program and a named file on secondary storage, and the chosen mode determines whether the program can read, overwrite or append data.
    • Read operations retrieve data from an opened file into program variables; read() returns the whole remaining content, readline() returns one line, and readlines() returns a list of lines.
    • Write operations send string data to an opened file; in write mode existing content is replaced, while append mode adds new data after existing content.
    • Closing a file releases the connection and ensures buffered data is saved; programs should close files after use, often using with open(...) as f: so closing happens automatically.
    • File paths and modes must be correct for the intended operation; attempting to read a file that does not exist, or writing to a read-only file, causes an error unless handled.
    • Data read from a text file arrives as strings, so numeric processing requires conversion such as int() or float() before calculation.
    • A record is a data structure that stores related fields about one entity, with each field having a name and a data type.
    • Fields are accessed by name, which improves readability and reduces errors compared with remembering positional indexes.
    • Records can be implemented in Python using dictionaries with string keys, or as objects of a class with attributes.
    • Multiple records can be held in a list, allowing iteration to search, sort, total or display data for many entities.
    • When records are stored in a text file, each line can represent one record and delimiters such as commas separate fields; parsing and type conversion are needed after reading.
    • Updating a record means assigning a new value to a named field, for example student['age'] = 15, without affecting other fields.
    • Identifies SELECT as choosing which columns appear in the result, and uses * only when every column is wanted.
    • Uses FROM to name the correct table, copying table and column names exactly as given in the question.
    • Applies WHERE with a correct comparison operator (such as <, >, <=, >=, =, !=) to filter rows, enclosing text values in single quotes.
    • Combines two or more conditions with AND or OR, showing correct logic where multiple criteria are required.
    • Predicts the exact output of a given query by filtering rows with WHERE first, then keeping only the columns named in SELECT.
    • Writes a complete statement in the order SELECT ... FROM ... WHERE, with clauses in the correct sequence.
    • Declares an array of a stated size and data type, for example scores as five integers, and explains that all elements share one identifier.
    • Reads and writes individual elements using correct indices, remembering that indexing commonly starts at 0 so the last index is size − 1.
    • Traverses a 1D array with a for loop whose counter runs from the first to the last valid index, processing each element once.
    • Uses two indices for a 2D array, the first for the row and the second for the column, and nests two loops to visit every cell.
    • Applies standard array processing such as finding a total, maximum or minimum, or searching for a value and recording its position.
    • Chooses an array over separate variables when several related values of the same type must be stored and processed together.
    • Defines a sub program as a named block of code that is defined once and called by name when required.
    • Distinguishes a procedure, which carries out a task and need not return a value, from a function, which returns a value to the point of call.
    • Explains that parameters are placeholders in the definition and arguments are the actual values passed when the sub program is called.
    • Describes how sub programs produce structured code by separating concerns, reducing duplication and making programs easier to read, test, debug and maintain.
    • Applies the idea to a concrete example, such as a function that returns the area of a circle from a radius parameter or a procedure that outputs a menu.
    • Explains how data flows into and out of a sub program, including local variables and the returned value of a function.
    • States that random number generation produces values that are not predictable in advance within a defined range.
    • Identifies how to call a library routine to generate a random number, giving the correct syntax and inclusive bounds for the language or pseudocode used.
    • Applies random values to a context, for example simulating a dice roll with a random integer from 1 to 6, or selecting a random item from an array.
    • Describes how generated values can be stored in variables, tested with selection statements or repeated inside loops.
    • Recognises that random number generation is a built-in library routine in most programming languages, avoiding the need to write the generation algorithm from scratch.
    • Uses OCR Reference Language correctly, writing `random(x, y)` for an integer from x to y inclusive, e.g. `random(1, 6)` for a die roll.
    • Explains that most language routines are pseudorandom, so values are predictable if the seed and algorithm are known.
    Examiner Tips
    • 💡Trace string operations on paper, writing the value after each step and counting characters carefully.
    • 💡When asked to manipulate a string, state the operation and show the result, e.g. slice, concatenate, change case.
    • 💡Check whether the question expects a single expression or a short sequence of statements, and keep code readable.
    • 💡Use quotation marks consistently and avoid mixing single and double quotes incorrectly.
    • 💡When asked to complete code, check the mode matches the task: 'r' for reading, 'w' for replacing, 'a' for adding.
    • 💡Show the close() call or a with open(...) as f: structure in written answers to demonstrate correct resource management.
    • 💡If a question asks for output, trace the file contents after each operation, remembering that write mode clears the file first.
    • 💡Use meaningful variable names for file objects and data so your code is easy to follow in an exam response.
    • 💡Define the fields and their data types before writing code, so your record structure is complete and consistent.
    • 💡Use meaningful field names such as 'price' or 'quantity' rather than vague names like 'x' or 'data'.
    • 💡When reading records from a file, show how you split each line and convert numeric fields before calculation.
    • 💡If asked to update a record, show the assignment to the named field and explain that other fields remain unchanged.
    • 💡Underline the table, the wanted columns and every condition in the question before writing anything, then map each underlined part to a clause.
    • 💡When asked for the output of a query, trace the rows through the WHERE filter first, then keep only the columns specified in the SELECT clause.
    • 💡As OCR J277 is an untiered exam, all candidates must be prepared to write full SQL statements from scratch, ensuring exact syntax for SELECT, FROM and WHERE clauses.
    • 💡Sketch the array as boxes with their index numbers before writing code, and mark the first and last valid indices.
    • 💡For a 2D array, label the rows and columns on your sketch and trace one complete inner loop before writing the nested loops.
    • 💡Check every loop bound against the declared size, since off-by-one errors are the most common lost mark in array questions.
    • 💡When asked to compare functions and procedures, state the return-value difference and give one short example of each.
    • 💡When writing code, define each sub program with a meaningful name and show clearly how it is called, including any arguments.
    • 💡When explaining structured code, link sub programs to at least two benefits such as reduced duplication and easier debugging.
    • 💡When writing pseudocode or code, clearly state the bounds for your random number generator, ensuring they match the scenario (e.g. 1 to 6 for a die).
    • 💡When a question asks for a simulation, state the range, how the value is stored in a variable, and how it is used in the program's logic.
    • 💡Check which language or pseudocode the question uses: OCR Reference Language `random(1, 6)` and Python `random.randint(1, 6)` both give a die roll but use different syntax.
    Common Mistakes
    • Using 1-based indexing when the language uses 0-based indexing. Correction: check the first character position and adjust slices accordingly.
    • Trying to change a string in place, such as name[0] = "J". Correction: build a new string, e.g. "J" + name[1:].
    • Concatenating a string and a number without casting, e.g. "Score: " + 10. Correction: cast with str(10) first.
    • Confusing len() with the last index. Correction: for a string of length n, valid indices are 0 to n - 1.
    • Forgetting to close a file after writing, which can leave data unsaved or the file locked; correction: always call close() or use a with block that closes automatically.
    • Using write mode when append was intended, which erases existing records; correction: choose 'a' to add data and 'w' only when replacing the whole file is deliberate.
    • Treating read data as a number without conversion, so arithmetic fails or concatenates strings; correction: convert with int() or float() before calculating.
    • Assuming read() returns a list of lines; correction: use readlines() for a list, or split() the result of read() if needed.
    • Confusing a record with an array, then accessing fields by numeric index; correction: use named keys or attributes so the meaning of each field is clear.
    • Storing numeric data as strings and then attempting arithmetic; correction: convert fields with int() or float() after reading or input.
    • Forgetting that a dictionary key must match exactly, including case; correction: use consistent key names and check spelling.
    • Treating a list of records as a single record; correction: loop over the list and access fields on each record in turn.
    • Writing SELECT * when the question asks for specific columns; the error is returning unwanted data, so the correction is to list only the named columns after SELECT.
    • Omitting quotes around text values, for example WHERE Town = 'Norwich' written without quotes; the error is that the database treats the word as a column name, so the correction is to include single quotes.
    • Confusing AND with OR in a filter; the error is returning too few or too many rows, so the correction is to test each condition separately and choose AND only when both must be true.
    • Putting WHERE before FROM or SELECT; the error is a syntax error, so the correction is to write the clauses in the order SELECT, FROM, WHERE.
    • Using a programming-language equality operator in a WHERE clause. Correction: use the SQL comparison operator shown in the specification or question.
    • Using an index equal to the array length, for example scores[5] on a five-element array; the error is an out-of-range access, so the correction is to loop while the counter is less than the length.
    • Swapping the row and column indices in a 2D array; the error is reading the wrong cell, so the correction is to fix the convention that the first index is the row and the second is the column.
    • Mixing data types in one array, such as names and ages together; the error breaks the same-type rule, so the correction is to use separate arrays or a record structure.
    • Saying a procedure always returns a value: correct this by stating that a procedure performs a task, whereas a function returns a value.
    • Confusing parameters with arguments: correct this by saying parameters appear in the definition and arguments are the values supplied at the call.
    • Writing one long program with repeated code instead of extracting reusable blocks: correct this by identifying repeated tasks and moving each into its own sub program.
    • Assuming a random function can return a value outside its stated bounds. Correction: state the bounds and note that both are inclusive, e.g. `random(1, 6)` returns 1 to 6.
    • Writing `random(n)` in OCR Reference Language. Correction: the routine takes two arguments, so write `random(1, 6)` for a die roll.
    • Writing `randint(1, 6)` in Python without importing. Correction: write `import random` then `random.randint(1, 6)`, or `from random import randint`.
    • Forgetting to store the generated random number in a variable before using it multiple times. Correction: assign the random value to a variable so the same value can be checked in multiple conditions.
    • Confusing the index of an array with the random value itself. Correction: generate a random integer within the bounds of the array's indices (e.g. 0 to length-1) and use it to access the element.