Skip to content
Cambridge IGCSE0478

Programming concepts

Computer Science 0478 Chapter Notes

What this chapter covers

Programming conceptsArraysFile handling
ShareWhatsAppPost
Programming concepts notes

Read online free. Download a watermarked copy with a free account.

Read the notes

The full Programming concepts notes as text: skim, search, and jump between subtopics.

~26 min read

1. Variables and constants

A variable can be changed during the execution of a program. A constant cannot be changed during the execution of a program.

Declare each one before it is used, with a meaningful name that has no spaces. Give a variable its starting value before you use it.

``` DECLARE Total : INTEGER CONSTANT MaxScore ← 50 Total ← 0 ```

Use `←` to assign a value. Do not use `=`, which is a relational operator.

Examiner insight

“Common errors included putting spaces in constant names, incorrectly stating a range of values and incorrectly including units in the value.” “Marks were lost if the constant name contained spaces or if the example stated would not work as a constant and would be better as a variable or an array.”

Worked example 13 marks

A program calculates the cost of tickets for a school trip. Every ticket costs 12. The number of tickets bought is input each time the program runs.

Identify one constant and one variable for this program, with a reason for each. Write the statement that declares the variable.

  1. 1

    Constant: `TicketPrice`, because its value never changes while the program runs [1]

  2. 2

    Variable: `NumberOfTickets`, because it is input and so changes each time [1]

  3. 3

    Declaration: `DECLARE NumberOfTickets : INTEGER` [1]

2. Basic data types

Choose the data type from the data. A whole number is an integer. A number that can have a fractional part is real.

A single letter, symbol or number is a char. Any combination of letters and numbers is a string. A value that is only TRUE or FALSE is Boolean.

The telephone number +44 7846398573 contains a symbol and a space, so it is a string.

Examiner insight

“Some candidates mixed up the two numeric data types: integer and real, for the examples of data in the question, while others mistakenly used database data types.” “Some candidates incorrectly used text as a data type.”

Worked example 13 marks

Complete the table by writing the most appropriate data type for each variable described.

variabledescriptionexample datadata type
`Age`the age of the student`16`
`TelephoneNumber`the telephone number of the student`+44 7846398573`
`Teenager`whether the student is a teenager or not`TRUE`
  1. 1

    Age: integer [1]

  2. 2

    TelephoneNumber: string [1]

  3. 3

    Teenager: Boolean [1]

3. Input, output, sequence and selection

Input reads a value into a variable. Output displays a value or a message. Give every input an input prompt so the user knows what to enter.

In sequence, statements run in the order they are written. Selection chooses which statements run.

``` OUTPUT "Enter your mark" INPUT Mark IF Mark >= 50 THEN OUTPUT "Pass" ELSE OUTPUT "Fail" ENDIF ```

Use `CASE` to test one variable against several values.

``` CASE OF Grade "A" : OUTPUT "Excellent" "B" : OUTPUT "Good" OTHERWISE OUTPUT "Keep trying" ENDCASE ```

Examiner insight

“Better candidates provided suitable reasons for choosing each type of conditional statement. For example IF can be used with complex conditions and CASE can be used to test for a large number of discrete values.” “Some candidates need to understand more about the structure of a CASE statement.”

Worked example 14 marks

A program asks the user for a mark out of 100. It outputs "Pass" if the mark is 50 or more. Otherwise it outputs "Fail". Write the pseudocode.

  1. 1

    An input prompt: `OUTPUT "Enter your mark out of 100"` [1]

  2. 2

    Input stored in a variable: `INPUT Mark` [1]

  3. 3

    Selection with the correct condition: `IF Mark >= 50 THEN OUTPUT "Pass"` [1]

  4. 4

    The other branch and the end of the statement: `ELSE OUTPUT "Fail"` and `ENDIF` [1]

4. Operators and library routines

Arithmetic operators: `+`, `–`, `/`, `*`, `^` (raised to the power of), `MOD` and `DIV`. Relational operators: `=`, `<`, `<=`, `>`, `>=` and `<>` (not equal to). Logical operators: `AND`, `OR` and `NOT`.

`MOD`, `DIV`, `ROUND` and `RANDOM` are library routines. `DIV(Total, 60)` turns a total in minutes into whole hours and `MOD(Total, 60)` gives the minutes left over. `ROUND(TotalRain / 365, 4)` rounds to four decimal places. `RANDOM() * 999 + 1` is credited for a random number between 1 and 1000 inclusive.

``` Hours ← DIV(Total, 60) Minutes ← MOD(Total, 60) AverageRain ← ROUND(TotalRain / 365, 4) GeneratedNumber ← RANDOM() * 999 + 1 ```

Examiner insight

“Common errors seen, included using OR instead of AND, <= instead of <, or omitting the variable Age for AND Age < 12.” “Most candidates were able to identify the correct purpose of MOD and DIV with only a few giving the correct pseudocode for MOD and DIV.”

Worked example 14 marks

Identify four operators that are not arithmetic operators from the list.

`/` `>` `<=` `+` `*`

`^` `AND` `DIV` `MOD` `NOT`

  1. 1

    `>` [1]

  2. 2

    `<=` [1]

  3. 3

    `AND` [1]

  4. 4

    `NOT` [1]

5. Iteration, totalling and counting

Iteration repeats statements. A count-controlled loop, `FOR … NEXT`, runs a pre-determined number of times. A pre-condition loop, `WHILE … DO … ENDWHILE`, tests its condition at the start, so it may not run at all.

A post-condition loop, `REPEAT … UNTIL`, checks the condition at the end of the loop, so it always runs at least once.

Totalling adds each value to a running total. Counting adds 1 each time. Set both to zero before the loop.

``` Total ← 0 Count ← 0 FOR Index ← 1 TO 10 INPUT Number Total ← Total + Number IF Number > 50 THEN Count ← Count + 1 ENDIF NEXT Index OUTPUT Total, Count ```

Examiner insight

“Candidates are advised, therefore, to learn distinctive features of the loop structures, such as the fact that the REPEAT loop is always executed at least once, and the WHILE loop condition is tested at the start, so may not run at all.” “Common errors seen, included confusing pre- and post-condition loops, and incorrectly identifying FOR as a statement to count.”

Worked example 14 marks

Give programming examples for a count-controlled loop and a post-condition loop. Describe each of the loops.

  1. 1

    Count-controlled loop example: `FOR` loop [1]

  2. 2

    Description: iterates a pre-determined number of times [1]

  3. 3

    Post-condition loop example: `REPEAT … UNTIL` [1]

  4. 4

    Description: checks the condition at the end of the loop, so it will always iterate once [1]

6. String handling

`LENGTH(Fact)` gives the number of characters. `UCASE(Fact)` gives the string in upper case. `LCASE(Fact)` gives it in lower case.

`SUBSTRING(Fact, 13, 7)` takes 7 characters from position 13. The first character can be position zero or one, so the mark scheme accepts 12 and 7 as well.

``` Fact ← "I learnt to program in computer science" OUTPUT LENGTH(Fact) OUTPUT UCASE(Fact) OUTPUT SUBSTRING(Fact, 13, 7) ```

The length counts every character, including the spaces. This string has 39.

Examiner insight

“Most candidates were able to store the phrase correctly and use the length function correctly but only a few were able to use the correct pseudocode uppercase function.” “A few incorrectly only counted the actual letters in the phrase.”

Worked example 15 marks

The string `"I learnt to program in computer science"` will be stored in the variable `Fact`

(a) Complete the pseudocode algorithm to:

• calculate and output the length of the string stored in the variable `Fact`

• output, in upper case, the string stored in the variable `Fact`

(b) Write the pseudocode statements to use a string function to output the word `program` taken from the string stored in the variable `Fact`

Do not declare any variables.

  1. 1

    (a) Correct use of `LENGTH` with `Fact` [1]

  2. 2

    Correct use of `UCASE` with `Fact` [1]

  3. 3

    The contents of both are output: `OUTPUT LENGTH(Fact)` and `OUTPUT UCASE(Fact)` [1]

  4. 4

    (b) Correct use of `SUBSTRING` with `Fact` [1]

  5. 5

    The two other parameters, 13 and 7 (accept 12 and 7), in an `OUTPUT` statement [1]

7. Nested statements

A nested statement sits inside another selection or iteration statement. Indent each level. The inner statement must end before the outer one ends.

You will not be asked to write more than three levels.

``` FOR Count ← 1 TO 20 REPEAT OUTPUT "Input a negative number" INPUT Number IF Number >= 0 THEN OUTPUT "Your number is not negative, please re-input" ELSE NegNumbers[Count] ← Number ENDIF UNTIL Number < 0 NEXT Count OUTPUT "The check has been completed" ```

Examiner insight

“Some candidates did not include all of the necessary elements to give a comprehensive response, such as not enabling the number to be re-input until a negative number is input.” “Some candidates incorrectly mixed Python code in with their pseudocode statements.”

Worked example 16 marks

Write the pseudocode for an algorithm to perform a validation check on each number as it is input to meet the following criteria:

• Input 20 numbers, one at a time.

• If a number is negative, store it in the current element of array `NegNumbers[]`

• If a number is not negative, ask for it to be input again until a negative number is input.

• When all 20 negative numbers have been stored, output a message to state the check has been completed.

Use appropriate input prompts and output messages to make the requirements clear to the user. Do not declare any arrays or variables for this algorithm.

  1. 1

    An appropriate loop to iterate for 20 inputs: `FOR Count ← 1 TO 20` [1]

  2. 2

    Input of a number: `INPUT Number` [1]

  3. 3

    A selection or condition-controlled loop to test if each input is negative: `REPEAT … UNTIL Number < 0` [1]

  4. 4

    Store a negative number in the correct array location: `NegNumbers[Count] ← Number` [1]

  5. 5

    Repeated input if the number is not negative, until it is negative [1]

  6. 6

    At least two outputs seen, from an input prompt, an error message or a completion message [1]

8. Subprograms and maintainable programs

A procedure and a function are subprograms. A function returns a value. A parameter is a value passed in: give each one a data type. A procedure or function may have up to three parameters.

A variable declared inside a subprogram is local to it. A global variable can be used in the whole program.

A procedure is run with `CALL`. A function call has no `CALL`: its returned value is stored.

``` FUNCTION Power(FirstNumber : INTEGER, SecondNumber : INTEGER) RETURNS INTEGER RETURN FirstNumber ^ SecondNumber ENDFUNCTION Value ← Power(A, B) ```

To make a program maintainable use comments, meaningful identifiers, and procedures and functions for the tasks within a program.

Examiner insight

“Common errors seen included not giving data types for the parameters or the function, incorrect use of ROUND, unsuccessfully attempting to use INT or MOD and incorrectly including the keyword CALL in the function call.” “Correct answers included use of commenting, ensuring identifiers have meaningful names and the use of procedures and functions for the tasks within a program.”

Worked example 15 marks

The function `Power(FirstNumber, SecondNumber)` returns the value of `FirstNumber` raised to the power of `SecondNumber`. `FirstNumber` and `SecondNumber` are integers.

Write pseudocode statements to define the function, and to call the function with the variables `A` and `B` and store the return value in the variable `Value`

  1. 1

    Define `FUNCTION Power` with `ENDFUNCTION` and `RETURNS INTEGER` (or `REAL`) [1]

  2. 2

    Correct parameters: `(FirstNumber : INTEGER, SecondNumber : INTEGER)` [1]

  3. 3

    Correct calculation: `FirstNumber ^ SecondNumber` [1]

  4. 4

    Return the calculated value: `RETURN` [1]

  5. 5

    Correct function call: `Value ← Power(A, B)` [1]

Recap

  • A variable can be changed while the program runs. A constant cannot.
  • Data types: integer, real, char, string, Boolean. Choose from the data.
  • Give every input a prompt. Use IF for conditions and CASE for several values.
  • MOD gives the remainder and DIV the whole number part. AND, OR and NOT are the logical operators.
  • FOR runs a set number of times. WHILE tests at the start. REPEAT tests at the end.
  • Set totals and counts to zero before the loop.
  • LENGTH counts every character. SUBSTRING takes a start position and a length.
  • Nested statements end from the inside out. A function call has no CALL.

9. Arrays and one-dimensional declarations

An array is a list of items of the same data type stored under a single name. Each item is an element, found by its index.

A one-dimensional (1D) array is declared with its index range and its data type. Using an array lets one loop deal with many values, so the program does not need a separate variable for each.

``` DECLARE Prices : ARRAY[1:40] OF REAL ```

The first index can be zero or one. The declaration fixes which, so `Prices[1:40]` has no element `Prices[0]`.

Examiner insight

“A common misinterpretation of the question was to describe an array incorrectly rather than explaining why it was an effective data structure for the reaction times.” “Common mistakes included declaring variables instead of arrays, not using meaningful names, leaving spaces within the name.”

Worked example 13 marks

Write the pseudocode to declare a one-dimensional array called `Prices` that stores 40 real numbers, with indices 1 to 40. Then write the statement that stores 2.50 in the third element.

  1. 1

    `DECLARE Prices : ARRAY[1:40] OF REAL`: the range `[1:40]` gives 40 elements [1]

  2. 2

    the data type is `REAL`, because prices have decimal places [1]

  3. 3

    `Prices[3] ← 2.50` stores the value in the element with index 3 [1]

10. Variables as indexes

The index in square brackets can be a variable. `Runners[Index]` means the element whose position is the current value of `Index`. When `Index` changes, the same line works on the next element.

The index must be a whole number inside the declared range. An index outside the range is an error: the algorithm crashes when it tries to use an element that does not exist.

Two arrays can share one index, so `Runners[Index]` and `Times[Index]` describe the same runner. Each value must go into the array that matches its type.

Examiner insight

“A few identified that the algorithm would crash when it tried to access an index that did not exist.” “Some candidates misunderstood that there were options and voters in position 1 of the relevant arrays and therefore began their iterations from index 2.”

Worked example 14 marks

This pseudocode algorithm is intended to store the names of up to 250 runners who finish a race. The names of the runners are stored in a one‑dimensional (1D) array Runners[] and their time in seconds in a one‑dimensional (1D) array Times[]. After the time for each runner has been entered into the array, the name of the runner and the time of the runner in minutes and seconds are displayed for verification.

Each runner takes 60 minutes or less to finish the race. A time of 60 minutes would be entered as 3600 seconds.

``` 01 DECLARE Runners : ARRAY[1:250] OF STRING 02 DECLARE Times : ARRAY[1:250] OF INTEGER 03 DECLARE Index : INTEGER 04 DECLARE RunName : STRING 05 DECLARE RunTime : STRING 06 DECLARE RunMins : INTEGER 07 DECLARE RunSecs : INTEGER 08 FOR Index ← 1 TO 250 09 OUTPUT "Enter a runner’s name and then time (in seconds) " 10 INPUT RunName 11 OUTPUT RunTime 12 RunMins ← DIV(RunTime, 60) 13 RunSecs ← DIV(RunTime, 60) 14 OUTPUT "Runner’s Name: ", RunName 15 OUTPUT "Time: ", RunMins, " Minutes ", RunSecs, " Seconds" 16 Runners[Index] ← RunMins 17 Times[Index] ← RunTime 18 NEXT Index ```

Identify the line numbers of four errors in the pseudocode and suggest corrections.

  1. 1

    Line 05: `DECLARE RunTime : STRING` should be `DECLARE RunTime : INTEGER` [1]

  2. 2

    Line 11: `OUTPUT RunTime` should be `INPUT RunTime` [1]

  3. 3

    Line 13: `RunSecs ← DIV(RunTime, 60)` should be `RunSecs ← MOD(RunTime, 60)` [1]

  4. 4

    Line 16: `Runners[Index] ← RunMins` should be `Runners[Index] ← RunName` [1]

11. Declaring and using 2D arrays

A two-dimensional (2D) array is a table. Its declaration gives two index ranges, rows first, then columns.

``` DECLARE Accounts : ARRAY[1:1000, 1:2] OF STRING ```

This table has 1000 rows and 2 columns, so 2000 elements. All elements have the same data type. `Accounts[Row, 2]` is the element in the row given by `Row` and in column 2.

A variable can stand for either index. Keep the row index and the column index in the declared order, or the wrong element is read.

Examiner insight

“Quite a few did not extract the information correctly from the 2D array and failed to use both dimensions.”

Worked example 14 marks

The purpose of this pseudocode algorithm is to find the name of a customer using an account ID, which contains letters and numbers. The name of the customer and the account ID are stored in the prepopulated two-dimensional (2D) array Accounts[]. The algorithm would then output the name of the customer.

For example, Accounts[1, 1] contains the account ID of the first customer and Accounts[1, 2] contains the name of the first customer.

``` 01 DECLARE Accounts : ARRAY[1:1000, 1:2] OF STRING 02 DECLARE Row : INTEGER 03 DECLARE AccountID : INTEGER 04 OUTPUT "Please enter an account ID " 05 OUTPUT AccountID 06 FOR Row ← 1 TO 1000 07 CASE OF AccountID = Accounts[Row, 1] 08 THEN 09 OUTPUT "The customer’s name is ", Accounts[1, 2] 10 ENDIF 11 NEXT Row ```

Identify the line numbers of four errors in the pseudocode and suggest corrections.

  1. 1

    Line 03: `DECLARE AccountID : INTEGER` should be `DECLARE AccountID : STRING`, because the ID contains letters and numbers [1]

  2. 2

    Line 05: `OUTPUT AccountID` should be `INPUT AccountID` [1]

  3. 3

    Line 07: `CASE OF AccountID = Accounts[Row, 1]` should be `IF AccountID = Accounts[Row, 1]` [1]

  4. 4

    Line 09: `Accounts[1, 2]` should be `Accounts[Row, 2]`, so the name comes from the row that matched [1]

12. Writing values into an array with iteration

To write values into an array, use a loop whose counter is the index, so each value is stored in the correct array location. A `FOR` loop counts for you: do not update its counter inside the loop.

``` FOR Index ← 1 TO 5 INPUT Marks[Index] NEXT Index ```

The same loop sets every element to a starting value: `Marks[Index] ← 0`. Where the number of inputs is not known, a `REPEAT` or `WHILE` loop with its own counter is used instead. Only that kind of counter is initialised before the loop and updated inside it by the programmer.

Examiner insight

“Setting all the elements of the given array to zero proved more challenging.” “Common errors included updating the loop counter within the loop and/or using incorrect commands, for example, DO, ENDLOOP or RANGE.”

Worked example 16 marks

Write the pseudocode for an algorithm to perform a validation check on each number as it is input, using the following criteria:

• Input one number at a time. • If the number is a whole number, store it in the current element of array Accepted[] • If the number is not a whole number, ask for it to be input again until it is a whole number. • When 15 whole numbers have been stored, output a message that states the check has been completed.

Use appropriate input prompts and output messages to make the requirements clear to the user.

You do not need to declare any arrays or variables for this algorithm.

  1. 1

    Appropriate loop to iterate for 15 inputs: `FOR Counter ← 1 TO 15` [1]

  2. 2

    Input of a number: `INPUT Value` [1]

  3. 3

    Test if the input is an integer, for example with `MOD(Value, 1) <> 0` [1]

  4. 4

    Repeated re-input if the number is not an integer, until it is an integer: `REPEAT … UNTIL MOD(Value, 1) = 0` [1]

  5. 5

    Store the integer in the correct array location: `Accepted[Counter] ← Value` [1]

  6. 6

    At least two outputs seen: an input prompt, an error message or the completion message [1]

  7. 7

    ``` FOR Counter ← 1 TO 15 REPEAT OUTPUT "Input a whole number" INPUT Value IF MOD(Value, 1) <> 0 THEN OUTPUT "Your number was not an integer, please re-input" ELSE Accepted[Counter] ← Value ENDIF UNTIL MOD(Value, 1) = 0 NEXT Counter OUTPUT "The check has been completed" ```

13. Reading values with nested iteration

To read every element of a 1D array, use one loop and output `Marks[Index]`. For a 2D array, use nested iteration: an outer loop for the rows and an inner loop for the columns.

``` FOR Row ← 1 TO 200 FOR Column ← 1 TO 2 OUTPUT Names[Row, Column] NEXT Column NEXT Row ```

The inner loop runs in full for each value of the outer loop. Close the inner loop before the outer one. The loop limits must match the declaration.

One `OUTPUT` statement is enough when it uses a loop counter for all array indices. Two statements, `OUTPUT Names[Row, 1]` and `OUTPUT Names[Row, 2]`, leave the inner loop with nothing to do.

Examiner insight

“Requirement 1 was not attempted well by most candidates as they did not use nested loop or use a 2D array as stated in the question.”

Worked example 14 marks

The last names and first names are stored in separate columns of a two‑dimensional (2D) array. The last names are stored in column 1 of the array. The array Names[] has already been declared as ARRAY[1:200, 1:2] OF STRING and it is already populated.

Write the pseudocode for an algorithm, using nested iteration, to output the contents of Names[]

  1. 1

    Outer loop with correct limits: `FOR Row ← 1 TO 200` [1]

  2. 2

    Inner loop with correct limits: `FOR Column ← 1 TO 2` [1]

  3. 3

    Output of both corresponding elements from the array before moving to the next name [1]

  4. 4

    … using an appropriate variable / loop counter for all array indices: `OUTPUT Names[Row, Column]` [1]

  5. 5

    ``` FOR Row ← 1 TO 200 FOR Column ← 1 TO 2 OUTPUT Names[Row, Column] NEXT Column NEXT Row ```

Recap

  • An array is a list of items of the same data type stored under a single name.
  • A 1D array is declared with one index range: `ARRAY[1:40] OF REAL`.
  • A 2D array has two ranges, rows first then columns: `ARRAY[1:1000, 1:2] OF STRING`.
  • A variable can be the index: `Runners[Index]`. It must stay inside the declared range.
  • Write values into an array with a loop whose counter is the index.
  • Read every element of a 2D array with nested iteration: rows outside, columns inside, one `OUTPUT` using both counters.
  • A `FOR` loop updates its own counter. A `WHILE` or `REPEAT` counter is initialised before the loop and updated inside it.

14. Why store data in a file

Data that a program uses can be stored in a file. The program reads the data from the file when it needs it.

Storing data in a file means it is stored permanently. It is not lost if the machine or program is switched off or crashes. The data can be used again later, kept as a backup, and moved to a different computer.

Examiner insight

“Most candidates stated one reason as to permanently store data, but most did not give a second reason.”

Worked example 11 mark

State one reason to store data in a file.

  1. 1

    The data is stored permanently (a non-volatile copy), so it is not lost if the machine is switched off. [1]

15. Opening and closing a file

A file must be opened before it is used and closed when the program has finished with it. The file name is written in quotes.

The statement that opens the file says what the file is opened for. `FOR READ` is for reading data from the file. `FOR WRITE` is for writing data to it.

``` OPENFILE "Scores.txt" FOR WRITE CLOSEFILE "Scores.txt" ```

Worked example 12 marks

Write the pseudocode statement that opens the file Scores.txt so that data can be written to it. Write the statement that finishes the use of the file.

  1. 1

    `OPENFILE "Scores.txt" FOR WRITE` [1]

  2. 2

    `CLOSEFILE "Scores.txt"` [1]

16. Reading from a file

To read a line of text, open the file `FOR READ`, use `READFILE`, then close the file. `READFILE` takes the file name and the variable that will hold the data.

The statement must read data from the file into a variable. Declare the variable with `DECLARE` and give it an appropriate name. The data read can be a single item of data or a line of text.

Worked example 14 marks

A list of names of the members of a club are stored in a file called Names.txt

Write the pseudocode statements to load a line of text from Names.txt and assign the line of text to an appropriately named variable.

  1. 1

    `DECLARE Name : STRING` (an appropriately named variable) [1]

  2. 2

    `OPENFILE "Names.txt" FOR READ` [1]

  3. 3

    `READFILE "Names.txt", Name` [1]

  4. 4

    `CLOSEFILE "Names.txt"` [1]

17. Writing to a file

To write a line of text, open the file `FOR WRITE`, use `WRITEFILE`, then close the file. `WRITEFILE` takes the file name and the data to store.

The data can be held in a variable. An input is first stored in a variable. The variable is then written to the file.

The data written can be a single item of data or a line of text. A mark scheme gives one mark each for the correct opening of the file, the correct writing to the file and the correct closing of the file.

Examiner insight

“Candidates who wrote pseudocode to input a string and then correctly made use of file handing functions to open a file, added the data that had been input to the file and then closed the file, achieved the marks. However, many candidates appeared to find this question challenging.” “Most candidates were aware of the correct pseudocode statement used to store a piece of data held in a variable to a text file.”

Worked example 13 marks

The new username is stored in the variable NewUsername

Write the pseudocode to store NewUsername to the file Username.txt

  1. 1

    `OPENFILE "Username.txt" FOR WRITE` (correct opening of file) [1]

  2. 2

    `WRITEFILE "Username.txt", NewUsername` (correct writing to file) [1]

  3. 3

    `CLOSEFILE "Username.txt"` (correct closing of file) [1]

Recap

  • A file stores data permanently, so it is not lost if the machine or program is switched off or crashes.
  • Open the file first: `OPENFILE "name" FOR READ` or `FOR WRITE`.
  • Read a line: `READFILE "name", Variable`. Write a line: `WRITEFILE "name", Data`.
  • Close the file last: `CLOSEFILE "name"`.
  • A mark scheme credits the declaration of an appropriately named variable.

End-of-chapter exercise

Test yourself on the whole chapter. Work through these before moving on.

  1. State the difference between a variable and a constant.2 marks
  2. State the most appropriate data type for each item of data. (a) A body temperature of 36.5 (b) The postcode "SW1A 2AA" (c) Whether a seat has been booked (d) The number of students in a class4 marks
  3. Write pseudocode that asks the user to enter two numbers and then outputs their sum. Use an input prompt for each number.4 marks
  4. A cinema gives a discount to people aged under 12 or over 65. Write the `IF` condition that is true when a person gets the discount.2 marks
  5. A video lasts 5000 seconds. Write expressions using `DIV` and `MOD` for the whole minutes and for the seconds left over. Give the value of each.3 marks
  6. What is output by this algorithm? ``` Total ← 0 FOR Index ← 1 TO 4 Total ← Total + Index * 2 NEXT Index OUTPUT Total ```3 marks
  7. The variable `Count` starts at 10. (a) How many times does this loop run? ``` REPEAT Count ← Count + 1 UNTIL Count > 5 ``` (b) The loop is rewritten as `WHILE Count <= 5 DO … ENDWHILE`, with `Count` again starting at 10. How many times does its body run? Explain why the two answers differ.3 marks
  8. The variable `Word` stores "computer science". The first character is position 1. (a) Write a statement to output the number of characters in `Word`. State the value output. (b) Write a statement to output only the word "science".4 marks
  9. A cycling club times 4 riders over one lap, in seconds. A time must be greater than 0. Any other time is rejected and asked for again. The algorithm should output the total time in minutes and seconds, and the number of riders who took less than 90 seconds. It contains three errors. ``` 01 Fast ← 0 02 FOR Rider ← 1 TO 4 03 Total ← 0 04 REPEAT 05 OUTPUT "Enter the lap time" 06 INPUT LapTime 07 UNTIL LapTime >= 0 08 Total ← Total + LapTime 09 IF LapTime <= 90 10 THEN 11 Fast ← Fast + 1 12 ENDIF 13 NEXT Rider 14 OUTPUT DIV(Total, 60), " min ", MOD(Total, 60), " s" 15 OUTPUT Fast ``` The times entered are 85, 0, 90, 130 and 75, in that order. (a) State the two lines output by the algorithm as it is written. (b) Identify the three errors and write each corrected line. (c) State the two lines output by the corrected algorithm for the same times.8 marks
  10. A bakery packs bread rolls in boxes of 12. A part-filled box still counts as a box. The number of rolls ordered is stored in the global variable `Rolls`. (a) Write a function `BoxesNeeded` with one integer parameter `Ordered`. It returns the number of boxes needed. Use `DIV`, `MOD` and a local variable `Boxes`. (b) A box costs 4.75. Write statements to call the function with `Rolls`, store the return value in `Needed`, and output the cost of the boxes divided by the number of rolls, rounded to 2 decimal places. (c) State the value returned when `Rolls` is 96 and when `Rolls` is 100. State the value output in (b) when `Rolls` is 100. (d) The statement `OUTPUT Boxes` is added to the end of the main program. Explain why it does not output the number of boxes.12 marks
  11. Write the pseudocode statement to declare a one-dimensional array called `Temperatures` that stores 30 real numbers, with indices 1 to 30.2 marks
  12. The array `Score[1:5]` holds the values 12, 8, 15, 9 and 20 in that order. State the value of `Score[4]` and the value of `Score[2 + 1]`.2 marks
  13. A cinema stores seat bookings in the 2D array `Seats[1:6, 1:10]` of STRING, with 6 rows and 10 columns. (a) State the number of elements in the array. (b) Write a statement that stores "taken" in row 4, column 7.2 marks
  14. The array `Marks[1:4]` holds 6, 9, 4 and 7. ``` Total ← 0 FOR Index ← 1 TO 4 Total ← Total + Marks[Index] NEXT Index OUTPUT Total / 4 ``` State the value that is output.3 marks
  15. The array `Readings` is declared as `ARRAY[1:8] OF INTEGER`. This loop fills it. ``` FOR Index ← 1 TO 9 INPUT Readings[Index] NEXT Index ``` Explain what goes wrong and correct the loop.2 marks
  16. Write pseudocode to input five names with a prompt and store them in the array `Names[1:5]`.4 marks
  17. The 2D array `Grid[1:2, 1:3]` has 2 rows and 3 columns. Row 1 holds 3, 5 and 2. Row 2 holds 4, 1 and 6. ``` Sum ← 0 FOR Row ← 1 TO 2 FOR Column ← 1 TO 3 IF Grid[Row, Column] > 3 THEN Sum ← Sum + Grid[Row, Column] ENDIF NEXT Column NEXT Row OUTPUT Sum ``` State the value that is output.3 marks
  18. The array `Grades[1:3, 1:4]` holds three students (rows) and four test marks (columns). Write pseudocode to output the total of the four marks for student 2 only.4 marks
  19. A café asks 8 customers to choose one of 4 drinks, numbered 1 to 4. The array `Choice[1:8]` holds 3, 1, 4, 3, 2, 3, 1 and 4 in that order. Every element of the array `Tally[1:4]` holds 0 before this code runs. ``` FOR Index ← 2 TO 8 Drink ← Choice[Index] Tally[Drink] ← Tally[Drink] + 1 NEXT Index Best ← 1 FOR Index ← 2 TO 4 IF Tally[Index] > Tally[Best] THEN Best ← Index ENDIF NEXT Index OUTPUT Best, " ", Tally[Best] ``` (a) State the four values in `Tally` after the first loop, and the two values that are output. (b) The code is meant to count every customer. Identify the one line that is wrong, correct it, and state the two values the corrected code outputs.6 marks
  20. A greenhouse has 3 plant beds. The 2D array `Moisture[1:14, 1:3]` is already populated with one soil reading for each of 14 days (rows) for each bed (columns). The 1D array `BedNames[1:3]` holds the name of each bed. The 1D array `DryDays[1:3]` has been declared but holds no values. A reading below 20 is a dry day. Write pseudocode, using nested iteration, to store the number of dry days for each bed in `DryDays[]` and to output the name of each bed with its number of dry days.6 marks
  21. A game keeps the player's score in a variable. State one reason for also storing the score in a file.1 mark
  22. State two reasons to store data in a file.2 marks
  23. Which pseudocode keyword retrieves a line of data from a file: `OPENFILE`, `READFILE` or `CLOSEFILE`?1 mark
  24. Write the pseudocode statement that opens the file Marks.txt so that data can be read from it. Write the statement that closes it.2 marks
  25. A programmer wants to store the variable Entry in the file Log.txt ``` OPENFILE "Log.txt" FOR READ WRITEFILE "Log.txt", Entry CLOSEFILE "Log.txt" ``` Identify the error and write the corrected line.2 marks
  26. The pseudocode should read a name from the file Names.txt into Name. The statements are in the wrong order. ``` READFILE "Names.txt", Name CLOSEFILE "Names.txt" OPENFILE "Names.txt" FOR READ ``` Write the statements in the correct order.3 marks
  27. A café keeps the dish of the day on the first line of Menu.txt Write the pseudocode to declare a variable called Dish and load that line of text into it.4 marks
  28. A hotel asks each guest for a name. The name is stored in the file Guests.txt Write the pseudocode to declare a variable, input the name into it and store it in the file.5 marks
  29. A weather station keeps the latest temperature on the first line of Temps.txt. This pseudocode should read that line into Reading and then store it in Daily.txt ``` DECLARE Reading : STRING OPENFILE "Temps.txt" FOR WRITE OPENFILE "Temps.txt", Reading CLOSEFILE "Temps.txt" WRITEFILE "Daily.txt", "Reading" CLOSEFILE "Temps.txt" ``` The pseudocode contains five errors. Write the corrected pseudocode.5 marks
  30. A running club keeps the name of its record holder on the only line of Fastest.txt. When the record is broken, the old name must be stored in Previous.txt and the new name, which is input, must be stored in Fastest.txt The variables OldHolder and NewHolder have already been declared. Write the pseudocode to do this. State two reasons why the club stores the names in files.10 marks

Go deeper

Practise and revise with member-only material for this chapter.

Free notes are just the start.

Unlock every Workbook and Chapter at a Glance, and generate your own worksheets and predicted papers.

Explore plans

Related chapters