UNIHIVE

Study Hub UNIPORT CSC 180.1

CSC 180.1 · Introduction to Computer Science and BASIC Programming

Lists, arrays and subscripts

One- and two-dimensional arrays, DIM, subscripts, and common array tasks: totals, largest value, searching and sorting.

Our notes

1 min read

Why arrays

An array (subscripted variable) stores many values under one name, each picked out by a subscript (index): A(1), A(2)... instead of A1, A2, A3. It makes loops over lists easy.

Declaring with DIM

DIM A(20) reserves A(0) or A(1) to A(20) (the first index depends on the dialect; classic BASIC starts at 0). Without DIM most BASICs allow up to index 10.
Two-dimensional: DIM M(3, 4) for a table of rows and columns (matrices, marks of students in subjects). String arrays: DIM N$(50).

Filling and using an array

10 DIM S(5)
20 FOR I = 1 TO 5
30 READ S(I)
40 NEXT I
50 LET T = 0
60 FOR I = 1 TO 5
70 LET T = T + S(I)
80 NEXT I
90 PRINT "TOTAL ="; T, "AVERAGE ="; T / 5
100 DATA 45, 62, 70, 38, 55
110 END
Output: TOTAL = 270, AVERAGE = 54.

Largest value

10 LET BIG = S(1)
20 FOR I = 2 TO 5
30 IF S(I) > BIG THEN BIG = S(I)
40 NEXT I
With the data above BIG = 70.

Linear search

Compare each element with the target until found. To find 38: checks 45, 62, 70, then finds 38 at position 4.

Bubble sort

Compare neighbours and swap if out of order; after each pass the largest remaining value "bubbles" to the end.
10 FOR P = 1 TO 4
20 FOR I = 1 TO 5 - P
30 IF S(I) > S(I+1) THEN T = S(I) : S(I) = S(I+1) : S(I+1) = T
40 NEXT I
50 NEXT P
45, 62, 70, 38, 55 becomes 38, 45, 55, 62, 70. For n items it needs at most n − 1 passes.

Two-dimensional example: matrix sum

For a 2 × 2 table M with rows (1, 2) and (3, 4), a double loop adds every element: total 10.

Exams usually ask

  • Explain arrays, subscripts and DIM.
  • Write programs to read N numbers into an array and find the total, average, largest or smallest.
  • Sort a list by bubble sort and show the passes.

Common mistake

Using a subscript outside the DIM size ("subscript out of range"), or forgetting that some dialects start at index 0.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All CSC 180.1 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.