Arrays and file handling
Arrays and files
- An array stores many values of the same type in one variable.
- A file lets a program keep data after it stops.
- Loops are the natural way to work through both.
One-dimensional arrays
- A 1D array is like a single list; each value is found by an index (a position number).
DECLARE scores : ARRAY[1:5] OF INTEGER
scores[1] ← 90
FOR i ← 1 TO 5
INPUT scores[i]
NEXT i
- A loop fills or reads the whole array.
Practice
An array is:
An array stores many same-type values under one name; each is accessed by its index.
Two-dimensional arrays
- A 2D array is like a table with rows and columns, using two indexes
[row, column].
DECLARE grid : ARRAY[1:3, 1:3] OF INTEGER
grid[2, 3] ← 8 // row 2, column 3
- You read a 2D array with a loop inside a loop (nested iteration).
Practice
In grid[2, 3], which cell is accessed?
The first index is the row, the second the column — row 2, column 3.
Practice
To fill or read a 2D array you use:
One loop steps through rows, an inner loop through columns — nested iteration.
File handling
- A program can store data in a file so it survives after the program stops.
- Open the file, use it, then close it:
OPENFILE "data.txt" FOR WRITE
WRITEFILE "data.txt", "Hello"
CLOSEFILE "data.txt"
- Always close a file when finished (use
FOR READto read it back).
Practice
The correct order for using a file is:
Open the file first, do the reading/writing, then close it.
Practice
You should always close a file when you have finished using it.
Closing saves any buffered data and frees the file for other programs.
You've got it
Key idea
- a 1D array is a list reached by one index; fill/read it with a loop
- a 2D array is a table reached by
[row, column]; use nested loops - file handling: OPENFILE (READ/WRITE) → READFILE/WRITEFILE → CLOSEFILE
- always close a file when done