Arrays and file handling

Computer Science · Programming. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science topics

The idea

An array stores many values of the same data type under one identifier. Each value is an element, and an index gives its position. A 1D array is a single list. A 2D array is a table with rows and columns, so each element needs two index values.

Arrays are useful because a loop can step through the index and process every element with the same few lines of code. One FOR loop handles a 1D array. Nested FOR loops handle a 2D array.

Data in variables and arrays is lost when the program ends. Storing data in a file keeps it, so the program can read it again the next time it runs.

Rules to remember

Common mistake

When a loop changes elements using other elements of the same array, students use the old values in their trace. Go one step at a time and use the values the array holds at that moment.

Worked example

An array Nums[1:5] holds 3, 8, 1, 6, 2. What is output?
Total ← 0
FOR i ← 2 TO 4
    Total ← Total + Nums[i]
NEXT i
OUTPUT Total

  1. The loop uses i = 2, 3 and 4 only, so Nums[1] and Nums[5] are not used.
  2. Nums[2] = 8, Nums[3] = 1 and Nums[4] = 6.
  3. Total = 0 + 8 + 1 + 6 = 15.

Answer: 15

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Procedures, functions and maintainable programsSingle-table databases and primary keys →Take a Computer Science test