IGCSE Computer Science · Area 2 · Algorithms, programming and logic

Programming

This topic is the language of Paper 2. You need to declare variables and constants, pick the right data type, take input and produce output, control the flow of a program with selection and iteration, use the operators and library routines the syllabus lists, handle strings, write procedures and functions with parameters, store data in one-dimensional and two-dimensional arrays, and read from and write to files. All of it is written in Cambridge pseudocode, and the marks are lost on the wording of statements, not on the ideas.

Not started

Syllabus coverage

  • Declare and use variables and constants
  • Understand and use the basic data types: integer, real, char, string and Boolean
  • Understand and use input and output
  • Understand and use the concept of sequence
  • Understand and use the concept of selection, including IF statements and CASE statements
  • Understand and use the concept of iteration, including count-controlled loops, pre-condition loops and post-condition loops
  • Understand and use the concepts of totalling and counting
  • Understand and use string handling: length, substring, upper and lower
  • Understand and use arithmetic, relational and logical operators
  • Understand and use nested statements, including nested selection and iteration
  • Understand what is meant by procedures, functions and parameters, and define and use procedures and functions with or without parameters
  • Understand and use local and global variables
  • Understand and use library routines: MOD, DIV, ROUND and RANDOM
  • Understand how to create a maintainable program, using meaningful identifiers, comments and procedures and functions
  • Declare and use one-dimensional (1D) and two-dimensional (2D) arrays, and understand their use, including the use of variables as indexes
  • Write values into, and read values from, an array using iteration, including nested iteration
  • Understand the purpose of storing data in a file to be used by a program
  • Open, close and use a file for reading and writing, including reading and writing single items of data and a line of text

Part of the IGCSE Computer Science syllabus 0478.

Programming: constructs and tracingThe three constructs look the same in every language; only the keywords change.A trace table is the fastest way to show you understand what a program does without running it.The same three constructs in codeSequencetotal <- 0price <- 2.50total <- price * 4SelectionIF mark >= 50 THEN grade <- "pass"ELSE grade <- "retry"ENDIFIterationFOR i <- 1 TO 10 total <- total + iNEXT iA trace table shows the runtotalioutput011233646one row per pass through the loopThe last value written to a variableis the one it keeps.Validate the input; verify the output.
The three programming constructs side by side, each shown as a block of Cambridge pseudocode and as the matching flowchart: sequence as a run of process boxes, selection as an IF statement with a decision diamond, and iteration as a FOR loop with control flowing back to the top of the loop.

Variables, constants and data types

A variable is a named store whose value can change while the program runs. Every variable is declared before it is used, with an identifier and a data type: DECLARE Score : INTEGER. The data type tells the computer what kind of value the variable holds and what can be done with it.

The five basic data types are integer, real, char, string and Boolean. An integer is a whole number, a real is a number capable of containing a fractional part, a char is a single character, a string is a sequence of zero or more characters, and a Boolean holds either TRUE or FALSE. Choosing the wrong type causes an error rather than a wrong answer: an average of 67.5 cannot be stored in a variable declared as an INTEGER.

A constant is a value that is set once and never changes while the program runs. It is declared with the keyword CONSTANT, for example CONSTANT HourlyRate ← 6.50. Only a literal can be used as the value of a constant, never a variable, another constant or an expression. Constants make a program easier to maintain, because the value appears in one place and can be updated once instead of being hunted down in every calculation that uses it.

Identifiers are the names given to variables, constants, arrays, procedures and functions. Cambridge pseudocode uses Pascal case, so NumberOfPlayers rather than number_of_players: letters and digits only, starting with a capital letter, with no underscore and no accented characters. Identifiers are case insensitive, so Countdown and CountDown must not be used as two different variables, and a keyword must never be used as an identifier.

The name should say what the value is. TotalScore and PupilName tell the next person what is being stored, which is part of what makes a program maintainable. T and P do not.

Data typeWhat it holdsExample declaration
INTEGERA whole numberDECLARE Counter : INTEGER
REALA number capable of containing a fractional partDECLARE TotalToPay : REAL
CHARA single characterDECLARE Initial : CHAR
STRINGA sequence of zero or more charactersDECLARE FirstName : STRING
BOOLEANOne of the two values TRUE or FALSEDECLARE GameOver : BOOLEAN
Real literals always have at least one digit on each side of the decimal point, so write 4.0 and 0.3 rather than 4. and .3. Char literals sit in single quotes and string literals sit in double quotes.

Input, output and sequence

Values are read into a program with INPUT and written out with OUTPUT. The identifier given to INPUT must be a variable, and it may be a single element of an array. OUTPUT can send several values at once if they are separated by commas, which is how text and values are mixed on one line: OUTPUT "You have ", Lives, " lives left".

An INPUT statement on its own gives the user no idea what to type, so a user prompt is placed immediately before it. OUTPUT "Enter the pupil's score" followed by INPUT Score is the standard pattern, and prompts, inputs and outputs are the three things an examiner looks for when you are asked to write or amend an algorithm.

Sequence means the statements are carried out one after another, in the order in which they are written. The order matters. Setting a total to 0 before a loop gives a correct total, while putting the same statement inside the loop wipes out the running total on every pass.

Data is checked as soon as it is entered. A validation check placed straight after the INPUT statement rejects data that is not sensible before the rest of the program tries to use it, which is why a program can tell you that the age you typed is not valid instead of crashing a few lines later.

  • INPUT <variable> reads one value into a variable.
  • OUTPUT <value(s)> writes one or more values, separated by commas.
  • Put an OUTPUT prompt immediately before every INPUT so the user knows what to type.
  • Statements run in sequence, so moving one statement changes the result of the whole program.
Every INPUT in an answer to an algorithm question should have a prompt in front of it. A mark is regularly awarded for the prompt alone.

Selection: IF and CASE statements

Selection lets a program choose between paths. An IF statement tests a condition and carries out the statements that follow it only when the condition is TRUE. A condition is always an expression that evaluates to a Boolean, such as Score >= 50, and it must never be written as a sentence.

The THEN and ELSE clauses are indented by two spaces, because they are continuations of the IF statement rather than separate statements, and every IF is closed with ENDIF. The ELSE clause is optional: without it, nothing at all happens when the condition is false.

A CASE statement compares one variable with several fixed values, and it is clearer than a long chain of IF statements. Each case clause holds a single value and a single statement, the clauses are indented by two spaces, and the whole statement ends with ENDCASE. An OTHERWISE clause, which must be the last case, runs when none of the other cases apply.

The cases are tested in order. As soon as one applies, its statement is carried out and the remaining cases are skipped, so control passes to the statement after ENDCASE. That is why the order of the cases matters whenever more than one of them could match.

Statements can be nested: an IF inside another IF, or a loop inside a loop. Cambridge will not ask you to write more than three levels of nesting, and each level is indented a further two spaces so that the structure can still be read.

ConstructUse it whenHow it is written
IF without ELSESomething should happen only when the condition is trueIF <condition> THEN ... ENDIF
IF with ELSEOne of two paths must always be takenIF <condition> THEN ... ELSE ... ENDIF
Nested IFA second decision depends on the first oneAn IF inside a THEN or ELSE clause, indented a further two spaces
CASEOne variable is being compared with several fixed valuesCASE OF <identifier> ... OTHERWISE ... ENDCASE
Write conditions as expressions, not as English. Score >= 50 is marked; 'if the score is fifty or more' is not. Relational operators give a Boolean result, which is exactly what IF needs.

Iteration: count-controlled, pre-condition and post-condition loops

Iteration repeats statements, and there are three loops to choose between. Picking the right one is part of the answer.

A count-controlled loop repeats a known number of times: FOR Index ← 1 TO 10, with NEXT Index at the end. The counter must be an INTEGER, both end values are included, and if the first value is larger than the second the statements are not carried out at all. A STEP can be added to change the increment, and the increment may be negative.

A pre-condition loop (WHILE ... DO ... ENDWHILE) tests its condition before the statements are run, so it runs zero or more times. A post-condition loop (REPEAT ... UNTIL) tests its condition after the statements have run, so it always runs at least once. A WHILE loop repeats while the condition is TRUE, whereas a REPEAT loop repeats until the condition becomes TRUE, which is the opposite of each other.

Totalling and counting are the two standard uses of iteration. Totalling sets a total to 0 before the loop and adds Total ← Total + Value inside it. Counting sets a count to 0 before the loop and adds Count ← Count + 1 inside it. Both variables must be set before the loop and never inside it, or the running value is wiped out on every pass.

Loops can be nested, with one loop inside another, and the inner loop runs right through for every single pass of the outer loop. That is how a table of values is worked through row by row.

LoopHow it decides to repeatHow many times it runs
FOR ... NEXTThe counter runs from a start value to an end valueA known number of times, decided before the loop starts
WHILE ... DO ... ENDWHILEThe condition is tested before the statementsZero or more times, because the test comes first
REPEAT ... UNTILThe condition is tested after the statementsOne or more times, because the statements run before the test
Nested loopThe inner loop finishes for every pass of the outer loopThe number of outer passes multiplied by the number of inner passes
WHILE repeats while the condition is TRUE and REPEAT UNTIL repeats until the condition is TRUE. Mixing them up gives a loop that never runs or a loop that never stops.

Operators, string handling and library routines

Arithmetic operators carry out calculations: +, -, *, / and ^ for a power. The integer operators DIV and MOD work on whole numbers. DIV returns the quotient with the fractional part discarded and MOD returns the remainder, so DIV(10, 3) returns 3 and MOD(10, 3) returns 1. Multiplication and division are worked out before addition and subtraction, and it is good practice to use brackets to make the order explicit in a long expression.

Relational operators compare two values and always produce a result of data type BOOLEAN. The six used are =, <, <=, >, >= and <> for not equal to.

Logical operators combine Boolean values, and only AND, OR and NOT are used. AND is TRUE only when both sides are TRUE, OR is TRUE when at least one side is TRUE, and NOT reverses a value. They let one condition test two things at once: IF Age >= 11 AND Age <= 18.

String handling uses four library routines. LENGTH returns the number of characters in a string, SUBSTRING returns a section of a string given a start position and a length, and UCASE and LCASE return the string or character in upper case or lower case. The first character of a string can be position zero or one depending on the system, so state which position you are counting from.

Library routines are ready-made operations you can call. ROUND(Value, 2) rounds a value to two decimal places, and RANDOM() returns a random number between 0 and 1 inclusive, which can be scaled when a whole number is wanted. ROUND(RANDOM() * 6, 0) gives a whole number from 0 to 6.

The routines are worth memorising with their results. LENGTH("Happy Days") returns 10, SUBSTRING("Happy Days", 1, 5) returns "Happy", UCASE("Happy") returns "HAPPY" and LCASE('W') returns 'w'.

Operator or routineTypeWhat it does
+ - * /ArithmeticAdd, subtract, multiply and divide
^ArithmeticRaises a value to a power, so Radius ^ 2 squares the radius
DIVArithmetic, integers onlyReturns the quotient with the fractional part discarded: DIV(10, 3) returns 3
MODArithmetic, integers onlyReturns the remainder: MOD(10, 3) returns 1, so MOD(Number, 2) is 0 when Number is even
= < <= > >= <>RelationalCompare two values and return TRUE or FALSE
AND OR NOTLogicalCombine or reverse Boolean values
ROUNDLibrary routineRounds a real value to a given number of decimal places
RANDOMLibrary routineReturns a random number between 0 and 1 inclusive
MOD is the operator worth remembering. MOD(Number, 2) is 0 when the number is even and 1 when it is odd, which is how a program tests for even numbers without dividing.

Procedures, functions and writing a maintainable program

A procedure is a named block of code that carries out a task. It is defined once and called whenever it is needed, using the keyword CALL, and it ends with ENDPROCEDURE. Writing the same instructions once inside a procedure rather than repeating them keeps a program short and leaves one place to correct when something changes.

A function works in the same way as a procedure except that it also returns a single value to the point at which it was called, and its definition states the data type of that value. The RETURN statement gives the value back. Because a function produces a value, it is called as part of an expression, such as OUTPUT ClassAverage(Total, Count), and CALL is never used with a function.

Parameters are the values passed into a procedure or function when it is called. They are named and given data types in the definition, and they are used as variables inside the routine. Cambridge will not use more than three parameters. Parameters make a routine general: the same procedure draws a line of any length if the length is passed to it.

Local variables are declared inside a procedure or function and exist only while it runs, so the rest of the program cannot see them. Global variables are declared outside and can be used anywhere in the program. Local variables are safer, because no other part of the program can change them by accident, and they keep routines independent of each other.

A maintainable program is one that somebody else can understand and change without breaking it. That means meaningful identifiers for variables, constants, arrays, procedures and functions; comments, written with // on their own line above the code they describe and at the same level of indentation; procedures and functions that each do one job; and consistent indentation so the structure is visible. A comment should explain why the code does something, not repeat what the line already says.

FeatureProcedureFunction
DefinitionPROCEDURE <identifier>(<parameters>) ... ENDPROCEDUREFUNCTION <identifier>(<parameters>) RETURNS <data type> ... ENDFUNCTION
Returns a valueNoYes, one value, given back by the RETURN statement
How it is calledCALL <identifier>(<values>) as a complete statementInside an expression, so CALL is never used
Typical useOutputting a heading, or printing a line of a receiptWorking out an average, or converting a score into a grade
A function returns a value and is called inside an expression; a procedure returns nothing and is called as a statement with CALL. Putting CALL in front of a function is an error.

Arrays: one-dimensional and two-dimensional

An array is a fixed-length structure of elements that are all of the same data type, and each element is reached by its index number. An array is declared with its lower and upper bounds: DECLARE StudentNames : ARRAY[1:30] OF STRING. It is good practice to state the lower bound, because the first index can be 0 or 1 in different systems, and in Cambridge pseudocode a lower bound of 1 is generally used.

A two-dimensional array has two indexes, which is how a table of values is stored: DECLARE NoughtsAndCrosses : ARRAY[1:3, 1:3] OF CHAR. In the main statements only one index value is used for each dimension, so a single square is NoughtsAndCrosses[2, 3].

Arrays are used with iteration, because an index can be a variable. FOR Index ← 1 TO 30 with StudentNames[Index] ← "" inside it sets every element to the empty string, and the same loop with an INPUT statement fills the array from the keyboard. That is the whole point of an array: one loop processes every element instead of thirty separate statements.

Nested iteration works through a two-dimensional array, with an outer loop for the rows and an inner loop for the columns, so that every element is visited exactly once. A seating plan, a table of marks with one row per pupil and a game board are all handled in this way.

TaskPseudocodeWhat it does
Declare a 1D arrayDECLARE Scores : ARRAY[1:20] OF INTEGERCreates 20 integer elements, indexed from 1 to 20
Declare a 2D arrayDECLARE Grid : ARRAY[1:5, 1:5] OF CHARCreates a 5 by 5 grid of characters
Write to one elementScores[3] ← 45Stores 45 in the third element of the array
Read one elementOUTPUT Scores[3]Outputs the value stored in the third element
Use a variable as an indexScores[Index] ← 0Writes to whichever element Index currently refers to
Fill a whole arrayFOR Index ← 1 TO 20 ... Scores[Index] ← 0 ... NEXT IndexSets every element of the array to 0
Work through a 2D arrayFOR Row ← 1 TO 5 ... FOR Column ← 1 TO 5 ... Grid[Row, Column] ... NEXT Column ... NEXT RowVisits every element of the grid exactly once
An index must be an integer and must lie inside the declared bounds. State the lower bound in your declaration and stay consistent with it, because an index outside the bounds causes an error.

File handling

Data held only in variables is lost as soon as the program stops. Storing data in a file means it can be read back the next time the program runs, so a list of club members survives between sessions and can be used by other programs as well.

A file is opened before it is used, and the mode must be stated: OPENFILE "Members.txt" FOR READ, or OPENFILE "Backup.txt" FOR WRITE. A file should be opened in only one mode at a time. Opening a file for WRITE creates a new file, so any data already stored in that file is lost.

Data is read with READFILE "Members.txt", NextName, which reads one item of data and assigns it to the variable, and written with WRITEFILE "Backup.txt", NextName. A single item of data or a whole line of text can be read or written in this way. When the program has finished with a file it must be closed with CLOSEFILE "Members.txt", so that the data is saved and the file is released for other programs to use.

Reading a file normally uses a loop, because the number of items in a file is rarely known in advance. Opening a file for READ when the file does not exist causes an error, so a well-written program checks before it tries.

  • OPENFILE <file identifier> FOR <READ or WRITE> opens a file, and the mode must always be stated.
  • READFILE <file identifier>, <variable> reads one item of data and assigns it to the variable.
  • WRITEFILE <file identifier>, <variable> writes one item of data into the file.
  • CLOSEFILE <file identifier> closes the file so that the data is saved and the file is released.
  • Opening a file for WRITE creates a new file and destroys any data already in it.
Open, use, close, in that order. An answer that reads or writes a file without opening it, or that never closes it, loses marks even when the rest of the algorithm is right.

Key terms you must be able to define

Variable
A named store whose value can change while the program is running. Every variable is declared with an identifier and a data type.
Constant
A value that is set once and never changes while the program runs. It is declared as CONSTANT <identifier> ← <value>, and only a literal may be used as its value.
INTEGER
A data type holding a whole number.
REAL
A data type holding a number capable of containing a fractional part.
CHAR
A data type holding a single character.
STRING
A data type holding a sequence of zero or more characters.
BOOLEAN
A data type holding one of the two values TRUE or FALSE. The result of every relational operation is of this type.
Identifier
The name given to a variable, constant, array, procedure or function. In Cambridge pseudocode identifiers use Pascal case, contain only letters and digits, and start with a capital letter.
Sequence
The construct in which statements are carried out one after another, in the order in which they are written.
Selection
The construct in which a program chooses between different paths, using an IF statement or a CASE statement.
Iteration
The construct in which statements are repeated, using a count-controlled, pre-condition or post-condition loop.
Count-controlled loop
A loop that repeats a known number of times, written as FOR <identifier> ← <value1> TO <value2> with NEXT <identifier> at the end.
Pre-condition loop
A loop that tests its condition before running the statements, written as WHILE <condition> DO ... ENDWHILE. It may run zero times.
Post-condition loop
A loop that tests its condition after running the statements, written as REPEAT ... UNTIL <condition>. It always runs at least once.
Totalling
Keeping a running total by setting the total to 0 before a loop and adding each value to it inside the loop.
Counting
Keeping a running count of how many items have been processed, by setting the count to 0 before a loop and adding 1 to it inside the loop.
Arithmetic operators
The operators used for calculations: +, -, *, / and ^, together with the integer operators DIV and MOD.
Relational operators
The operators used to compare two values: =, <, <=, >, >= and <>. The result is always of data type BOOLEAN.
Logical operators
The operators used to combine Boolean values: AND, OR and NOT.
Library routine
A ready-made operation that can be called from a program. The routines used are MOD, DIV, ROUND and RANDOM, together with the string routines LENGTH, SUBSTRING, UCASE and LCASE.
String handling
Working with the characters in a string using LENGTH, SUBSTRING, UCASE and LCASE. The first character of a string can be position zero or one.
Nested statement
A statement placed inside another statement, such as an IF inside an IF or a loop inside a loop. Cambridge will not require more than three levels of nesting.
Parameter
A value passed into a procedure or function when it is called. Parameters are named and given data types in the definition and are used as variables inside the routine. There are never more than three.
Procedure
A named block of code that carries out a task but returns no value. It is called using the keyword CALL as a complete program statement.
Function
A named block of code that returns a single value to the point at which it was called, using the keyword RETURN. It is called as part of an expression, never with CALL.
Local variable
A variable declared inside a procedure or function that exists only while that routine runs, so no other part of the program can use or change it.
Global variable
A variable declared outside any procedure or function, which can be used by every part of the program.
One-dimensional array
A fixed-length structure of elements of identical data type, reached by a single index, declared as DECLARE <identifier> : ARRAY[<lower>:<upper>] OF <data type>.
Two-dimensional array
A structure of elements reached by two indexes, which is how a table or a grid is stored, declared as DECLARE <identifier> : ARRAY[<l1>:<u1>, <l2>:<u2>] OF <data type>.
File handling
Storing data in a file so that it can be used again by a program, using OPENFILE with a mode of READ or WRITE, READFILE, WRITEFILE and CLOSEFILE.
Maintainable program
A program that is easy to read, test and change, because it uses meaningful identifiers, comments, procedures and functions, and consistent indentation.

Applied to real systems

Cambridge sets 0478 in systems you already use - a phone, a school network, a supermarket till, a website, a bank. Use these as models for how to apply the theory to a context you have not seen before, then write your own.

In a vending machine

Giving change is a job for DIV and MOD. If 65p is owed, DIV(65, 50) gives 1 fifty-pence coin and MOD(65, 50) gives 15 to be paid next; DIV(15, 10) gives 1 ten-pence coin and MOD(15, 10) gives 5; and DIV(5, 5) gives 1 five-pence coin with nothing left over. The price of each item is held in a constant, so when a price changes only one line of the program needs updating.

In a school office

A program that produces end-of-term reports stores each pupil's marks in a one-dimensional array, one element per subject, and adds them up with a FOR loop. The average is a real number, so the total is declared as REAL and rounded before it is printed with ROUND(Total / Count, 1), which stops the report showing a mark like 67.33333.

In a quiz game

A quiz keeps asking questions with a WHILE loop while the player still has lives left, uses a Boolean variable to record whether the last answer was correct, and calls RANDOM() to choose which question comes next. The questions and their answers are held as strings in a two-dimensional array, so question three and its answer sit in the same row of the grid.

In a shop's stock system

Stock levels are read from a file when the program starts and written back to it when the program closes. OPENFILE "Stock.txt" FOR READ brings the existing data in, READFILE fills the variables one at a time inside a loop, and CLOSEFILE releases the file at the end so that the updated levels are saved for the next day.

In a payroll program

The rate of pay is held in a constant, CONSTANT HourlyRate ← 6.50, so it appears in one place in the program. The function GrossPay(Hours : REAL) RETURNS REAL works out the pay for each member of staff, and because it is a function its value can be used straight inside an expression such as OUTPUT GrossPay(38.5).

In a text messaging app

Checking a username uses string handling. LENGTH(UserName) tests that it is long enough, SUBSTRING(UserName, 1, 1) takes the first character to check that it is a letter, and UCASE turns the whole name into capitals before it is compared with names already taken, so that sam and SAM are treated as the same name.

Flashcards

Click a card to flip it. Mark honestly — the tracker uses this.

Q1How is an integer variable declared?
DECLARE Counter : INTEGER. Every variable is declared with its identifier and its data type before it is used.
Q2Name the five basic data types.
Integer (a whole number), real (a number that can contain a fractional part), char (a single character), string (a sequence of zero or more characters) and Boolean (TRUE or FALSE).
Q3How is a constant declared, and what may be used as its value?
CONSTANT HourlyRate ← 6.50. Only a literal may be used, never a variable, another constant or an expression.
Q4What does INPUT do, and what must the identifier be?
INPUT <variable> reads a value into a variable, which may be a single element of an array. An OUTPUT prompt is placed before it so the user knows what to type.
Q5What is the difference between a pre-condition loop and a post-condition loop?
A pre-condition loop (WHILE ... DO ... ENDWHILE) tests its condition first and may run zero times; a post-condition loop (REPEAT ... UNTIL) tests the condition last and always runs at least once.
Q6What do DIV(17, 5) and MOD(17, 5) return?
DIV returns the quotient with the fractional part discarded, so 3. MOD returns the remainder, so 2.
Q7Name the three logical operators and say what each does.
AND is TRUE only when both sides are TRUE, OR is TRUE when at least one side is TRUE, and NOT reverses a Boolean value.
Q8What does SUBSTRING("Happy Days", 1, 5) return, and what does LENGTH("Happy Days") return?
SUBSTRING returns "Happy" and LENGTH returns 10. SUBSTRING takes a start position and a length.
Q9What is the difference between a procedure and a function?
A procedure carries out a task and returns no value, so it is called with CALL as a statement. A function returns a single value, states its data type in the definition, and is called inside an expression.
Q10What is the difference between a local variable and a global variable?
A local variable is declared inside a procedure or function and exists only while it runs. A global variable is declared outside and can be used anywhere in the program.
Q11How is a two-dimensional array declared, and how is one element accessed?
DECLARE Grid : ARRAY[1:5, 1:5] OF CHAR declares it, and Grid[2, 3] accesses one element, using one index value for each dimension.
Q12Give the four file handling commands in the order they are used.
OPENFILE with a mode of READ or WRITE, then READFILE or WRITEFILE, and finally CLOSEFILE. Opening for WRITE creates a new file and destroys any existing data in it.
0 of 12 marked as known

Exam-style questions

8 questions, 26 marks. Write your answer, then reveal the mark scheme and tick each point you actually made. Answering honestly here is what makes the rest of the site useful.

StateAO11 mark
A program works out the average mark of a class. State a suitable data type for the variable that will store the average.

Mark scheme — tick each point you actually made

Examiner tip: One mark, one data type. INTEGER would lose the decimal places, and a string or a char cannot be used in a calculation.
IdentifyAO22 marks
The following declaration is used in a program. DECLARE Total : INTEGER The program then tries to store the value 67.5 in Total. Identify the error and state how the declaration should be corrected.

Mark scheme — tick each point you actually made

Examiner tip: Name the mismatch between the value and the data type, then write the corrected declaration exactly as it should appear.
DescribeAO13 marks
Describe the difference between a pre-condition loop and a post-condition loop, and state one occasion when a post-condition loop must be used rather than a pre-condition loop.

Mark scheme — tick each point you actually made

Examiner tip: Give both halves of the difference and then a genuine example where the test cannot come first, such as asking for input before it can be checked.
StateAO14 marks
State what each of the following returns. DIV(17, 5) MOD(17, 5) LENGTH("Happy Days") UCASE("Happy")

Mark scheme — tick each point you actually made

Examiner tip: These are recalled answers, so learn them as facts. Count the characters in the string carefully, including the space between the two words.
DemonstrateAO24 marks
A program stores ten scores in a one-dimensional array called Scores. The following algorithm should output the largest score, but the lines inside the loop are missing. Maximum ← Scores[1] FOR Index ← 2 TO 10 <missing lines> NEXT Index OUTPUT Maximum Demonstrate how the algorithm should be completed by supplying the missing lines.

Mark scheme — tick each point you actually made

Examiner tip: The comparison must use Scores[Index] against Maximum, and the replacement must go from the array element into Maximum, not the other way round. Do not forget ENDIF.
IdentifyAO23 marks
The following algorithm should output the average of twenty numbers, but it does not work correctly. Count ← 0 FOR Index ← 1 TO 20 INPUT Number Total ← Total + Number Count ← Count + 1 NEXT Index Average ← Total / Count OUTPUT Average Identify the error and suggest a correction.

Mark scheme — tick each point you actually made

Examiner tip: The Count variable is correct, so leave it alone. Name the variable at fault, write the correction as a statement, and say what goes wrong without it.
ExplainAO14 marks
Explain what is meant by a parameter, and give one reason why procedures and functions are used in a program.

Mark scheme — tick each point you actually made

Examiner tip: Say where the parameter comes from, where it is declared and how it is used. For the second part, give a reason about the program rather than a reason about typing less.
DescribeAO25 marks
A program is meant to copy the contents of the file Members.txt into the file Backup.txt. The statements below are in the wrong order. READFILE "Members.txt", LineOfText OPENFILE "Backup.txt" FOR WRITE CLOSEFILE "Backup.txt" OPENFILE "Members.txt" FOR READ CLOSEFILE "Members.txt" WRITEFILE "Backup.txt", LineOfText Describe the order in which the statements should be carried out and state what each one does.

Mark scheme — tick each point you actually made

Examiner tip: Both files must be open before anything is read or written, so the two OPENFILE statements come first. Closing a file before it has been used, or forgetting to close it, loses marks.

Exam technique for this topic

  • Write pseudocode, not Python or Java. On Paper 2 the logic is what is marked, and a solution written in a programming language scores nothing except in the 15-mark scenario question.
  • Use the syllabus keywords exactly and in upper case: DECLARE, CONSTANT, INPUT, OUTPUT, IF ... THEN ... ENDIF, FOR ... NEXT, WHILE ... DO ... ENDWHILE, REPEAT ... UNTIL, CASE OF ... ENDCASE, CALL and RETURN.
  • Indent every statement that sits inside another statement. THEN, ELSE and CASE clauses are indented by two spaces, and statements inside a loop are indented by four.
  • Set totalling and counting variables to 0 before the loop, never inside it, and choose the right integer operator: DIV for the whole-number quotient and MOD for the remainder.
  • Match the data type to the value. Use INTEGER for a count, REAL for an average or any value with a decimal point, CHAR for a single character in single quotes, and STRING in double quotes.

Why students lose marks here

A student wroteA student wrote the assignment the wrong way round: 10 ← Score.
Why it loses marksThe arrow always points from the value to the variable, because the value on the right is stored in the identifier on the left. Written this way round the statement tries to change the number 10, which is impossible, and the mark is lost.
The answer that scoresThe correct statement is Score ← 10, which stores the value 10 in the variable Score. The assignment operator ← replaces whatever was in the variable, so Score ← Score + 1 increases Score by one by working out the right-hand side first and then storing the result.
A student wroteA student declared DECLARE AverageMark : INTEGER and then used it to store the average mark of a class, which came out as 67.5.
Why it loses marksA value with a fractional part cannot be stored in an INTEGER variable, which holds whole numbers only. Either the program reports an error or the 0.5 is lost, and either way the answer is wrong.
The answer that scoresDeclare the variable as REAL, because an average can contain a fractional part: DECLARE AverageMark : REAL. Use INTEGER only for values that are whole numbers by their nature, such as the number of pupils in a class or a count of correct answers.
A student wroteA student put Total ← 0 inside a FOR loop that was meant to add up ten numbers, so the total only ever held the last number entered.
Why it loses marksSetting the total to 0 inside the loop wipes out everything added so far on every pass. The loop then runs ten times but only the final value survives, so the total is wrong and the average worked out from it is wrong too.
The answer that scoresInitialise before the loop and update inside it: Total ← 0 comes before the FOR statement, and Total ← Total + Number sits inside the loop. The same rule applies to a counting variable, which must be set to 0 before the loop and increased by 1 inside it.
A student wroteA student called a function using CALL, writing CALL Average(Total, Count).
Why it loses marksA function returns a value, so it is called as part of an expression rather than as a statement. CALL is used only with procedures, and putting it in front of a function loses the mark for the call.
The answer that scoresUse the function inside an expression, for example OUTPUT Average(Total, Count) or AverageScore ← Average(Total, Count). Use CALL only for a procedure, such as CALL DisplayHeading, which returns no value.
A student wroteA student wrote a loop as WHILE Count < 10 DO ... UNTIL Count = 10.
Why it loses marksThe two kinds of loop have been mixed together. A WHILE loop is a pre-condition loop and is closed with ENDWHILE, while REPEAT UNTIL is a post-condition loop that tests its condition at the end. The mixture cannot be executed and shows the examiner that the difference between the two loops is not understood.
The answer that scoresChoose one form and complete it. A pre-condition loop is WHILE Count < 10 DO ... ENDWHILE, which may run zero times. A post-condition loop is REPEAT ... UNTIL Count = 10, which always runs at least once and stops when the condition becomes true.