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.

In simpler words

An array holds many values of the same type under one name. Each value has a position number, called an index. A 1D array is a list. A 2D array is a table, so you need a row and a column. A loop can go through every item. Data in arrays is lost when the program stops. Files keep data for next time.

An everyday comparison

A 1D array is like a row of numbered lockers in a school corridor. Each locker holds one item, and you find it by its number. A 2D array is like a block of flats, where you need the floor and the door number. The comparison stops working because every element must hold the same data type, unlike lockers.

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.

In the exam

Write a full declaration such as DECLARE Grid : ARRAY[1:5, 1:8] OF INTEGER. Use a FOR loop over the index to fill or read a 1D array, and nested loops for 2D. For file handling, write the steps in order: OPENFILE with READ or WRITE, READFILE or WRITEFILE, then CLOSEFILE. In a trace table, update values one step at a time.

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