ZetCode

Modula-2 arrays

last modified November 26, 2026 Modula-2

An array is a fixed number of elements of one type, selected by an index. In Modula-2 the bounds of an array are part of its type and are fixed at compile time. The index may be a range of whole numbers, characters or booleans, so an array need not start at 0 or 1.

Declaring an array

ARRAY [low..high] OF T declares an array with one element of type T for each index from low to high. An element is selected with the index in square brackets.

week.mod
MODULE week;

FROM InOut IMPORT WriteString, WriteLn, WriteInt, WriteCard;

VAR
  temp: ARRAY [1..7] OF INTEGER;
  day: CARDINAL;
  sum: INTEGER;

BEGIN
  temp[1] := 4;  temp[2] := 7;  temp[3] := 3;  temp[4] := -2;
  temp[5] := 0;  temp[6] := 5;  temp[7] := 9;
  sum := 0;
  FOR day := 1 TO 7 DO
    WriteString("Day ");
    WriteCard(day, 0);
    WriteInt(temp[day], 4);
    WriteLn;
    sum := sum + temp[day]
  END;
  WriteString("Average: ");
  WriteInt(sum DIV 7, 0);
  WriteLn
END week.

The array holds seven temperatures, indexed from 1 to 7. The elements are set one by one; Modula-2 has no array literals in PIM. The FOR loop visits every index, prints the element and adds it to the sum.

$ gm2 week.mod -o week
$ ./week
Day 1   4
Day 2   7
Day 3   3
Day 4  -2
Day 5   0
Day 6   5
Day 7   9
Average: 3

Index types

The index type may be any subrange of a whole-number type, CHAR or BOOLEAN. The index expression must have that type: a character array is indexed by characters.

indexes.mod
MODULE indexes;

FROM InOut IMPORT WriteString, WriteLn, WriteCard, Write;

VAR
  minimum: ARRAY ['A'..'E'] OF CARDINAL;
  parity: ARRAY BOOLEAN OF CARDINAL;
  grade: CHAR;
  n: CARDINAL;

BEGIN
  minimum['A'] := 90;
  minimum['B'] := 80;
  minimum['C'] := 65;
  minimum['D'] := 50;
  minimum['E'] := 0;
  FOR grade := 'A' TO 'E' DO
    Write(grade);
    WriteString(" from");
    WriteCard(minimum[grade], 3);
    WriteString(" points");
    WriteLn
  END;

  parity[FALSE] := 0;
  parity[TRUE] := 0;
  FOR n := 1 TO 25 DO
    INC(parity[ODD(n)])
  END;
  WriteString("Odd: ");
  WriteCard(parity[TRUE], 0);
  WriteString(", even: ");
  WriteCard(parity[FALSE], 0);
  WriteLn
END indexes.

minimum is indexed by the grade letters 'A' to 'E', and a FOR loop over the letters walks through it. parity has two elements, FALSE and TRUE; the expression ODD(n) selects the counter to increase, so no IF is needed.

$ gm2 indexes.mod -o indexes
$ ./indexes
A from 90 points
B from 80 points
C from 65 points
D from 50 points
E from  0 points
Odd: 13, even: 12

Array types and assignment

An array type declared in a TYPE section can be used for several variables. Variables of the same array type can be assigned as a whole; the assignment copies every element.

copies.mod
MODULE copies;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

CONST
  Size = 5;

TYPE
  Scores = ARRAY [1..Size] OF CARDINAL;

VAR
  before, after: Scores;
  i: CARDINAL;

BEGIN
  FOR i := 1 TO Size DO
    before[i] := i * 10
  END;
  after := before;
  after[3] := 99;
  WriteString("before:");
  FOR i := 1 TO Size DO
    WriteCard(before[i], 4)
  END;
  WriteLn;
  WriteString("after: ");
  FOR i := 1 TO Size DO
    WriteCard(after[i], 4)
  END;
  WriteLn
END copies.

The constant Size sets the bounds of the type and the limits of the loops, so the size is changed in one place. After after := before the two arrays are independent copies: changing after[3] leaves before as it was.

$ gm2 copies.mod -o copies
$ ./copies
before:  10  20  30  40  50
after:   10  20  99  40  50

Arrays as parameters

A procedure parameter may have a named array type. A value parameter receives a copy of the whole array; a VAR parameter works on the caller's array.

prices.mod
MODULE prices;

FROM InOut IMPORT WriteString, WriteLn;
FROM RealInOut IMPORT WriteReal;

CONST
  Items = 4;

TYPE
  PriceList = ARRAY [1..Items] OF REAL;

VAR
  list: PriceList;

PROCEDURE Total(p: PriceList): REAL;
VAR
  i: CARDINAL;
  sum: REAL;
BEGIN
  sum := 0.0;
  FOR i := 1 TO Items DO
    sum := sum + p[i]
  END;
  RETURN sum
END Total;

PROCEDURE Discount(VAR p: PriceList; percent: REAL);
VAR
  i: CARDINAL;
BEGIN
  FOR i := 1 TO Items DO
    p[i] := p[i] * (100.0 - percent) / 100.0
  END
END Discount;

BEGIN
  list[1] := 12.5;
  list[2] := 8.0;
  list[3] := 23.9;
  list[4] := 5.6;
  WriteString("Total:");
  WriteReal(Total(list), 10);
  WriteLn;
  Discount(list, 20.0);
  WriteString("After a 20% discount:");
  WriteReal(Total(list), 10);
  WriteLn
END prices.

Total reads its copy of the price list, and Discount changes the prices in the caller's array. The parameter type must be a type name such as PriceList: a parameter cannot be declared as ARRAY [1..4] OF REAL directly. Copying a large array for a value parameter costs time, which is one reason to pass it as a VAR parameter even when it is only read.

$ gm2 prices.mod -o prices
$ ./prices
Total: 50.000000
After a 20% discount: 40.000000

Comparing arrays

Arrays can be assigned as a whole but not compared. The operators = and # do not accept array operands.

compare.mod
MODULE compare;

FROM InOut IMPORT WriteString, WriteLn;

TYPE
  Code = ARRAY [1..4] OF CARDINAL;

VAR
  a, b: Code;

BEGIN
  a[1] := 1; a[2] := 9; a[3] := 8; a[4] := 4;
  b := a;
  IF a = b THEN
    WriteString("same code")
  END;
  WriteLn
END compare.

The compiler rejects the comparison a = b and reports both operands.

$ gm2 compare.mod -o compare
compare.mod:9:3: error: In program module ‘compare’: not expecting an array variable as an operand for either comparison or binary operation
    9 |   a, b: Code;
      |   ^
compare.mod:9:3: error: it was declared as a variable
compare.mod:9:6: error: not expecting an array variable as an operand for either comparison or binary operation
    9 |   a, b: Code;
      |      ^
compare.mod:9:6: error: it was declared as a variable

An equality procedure

Two arrays are compared element by element. A function procedure returns FALSE at the first difference and TRUE when the loop finds none.

equal.mod
MODULE equal;

FROM InOut IMPORT WriteString, WriteLn;

TYPE
  Code = ARRAY [1..4] OF CARDINAL;

VAR
  a, b: Code;

PROCEDURE Equal(VAR x, y: Code): BOOLEAN;
VAR
  i: CARDINAL;
BEGIN
  FOR i := 1 TO 4 DO
    IF x[i] # y[i] THEN
      RETURN FALSE
    END
  END;
  RETURN TRUE
END Equal;

PROCEDURE Check(VAR x, y: Code);
BEGIN
  IF Equal(x, y) THEN
    WriteString("same code")
  ELSE
    WriteString("different codes")
  END;
  WriteLn
END Check;

BEGIN
  a[1] := 1; a[2] := 9; a[3] := 8; a[4] := 4;
  b := a;
  Check(a, b);
  b[4] := 5;
  Check(a, b)
END equal.

Equal takes its arrays as VAR parameters to avoid copying them, although it does not change them. The early RETURN inside the loop ends the comparison as soon as the answer is known.

$ gm2 equal.mod -o equal
$ ./equal
same code
different codes

Index out of range

An index outside the bounds of the array is an error. GNU Modula-2 does not check indexes in the default build; -fsoft-check-all adds the checks.

bounds.mod
MODULE bounds;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

VAR
  slots: ARRAY [1..3] OF CARDINAL;
  other: CARDINAL;
  i: CARDINAL;

BEGIN
  other := 7;
  FOR i := 1 TO 4 DO
    slots[i] := 100
  END;
  WriteString("other = ");
  WriteCard(other, 0);
  WriteLn
END bounds.

The loop runs one step too far and writes slots[4], which does not exist. Without checks the program writes into memory after the array and finishes as if nothing happened. With -fsoft-check-all it stops at the bad access with exit status 134.

$ gm2 bounds.mod -o bounds
$ ./bounds
other = 7
$ gm2 -fsoft-check-all bounds.mod -o bounds
$ ./bounds
bounds.mod:13:12: In program module bounds
bounds.mod:13:12:if this access to the static array is ever made then the index will be out of bounds in the 1st array subscript
Aborted (core dumped)
$ echo $?
134

Multidimensional arrays

An array with two index ranges is a table. The ranges are separated by a comma in the declaration, and so are the indexes when an element is selected.

seats.mod
MODULE seats;

FROM InOut IMPORT WriteString, WriteLn, WriteCard, Write;

CONST
  Rows = 4;
  Cols = 8;

VAR
  taken: ARRAY [1..Rows], [1..Cols] OF BOOLEAN;
  r, c, free: CARDINAL;

BEGIN
  FOR r := 1 TO Rows DO
    FOR c := 1 TO Cols DO
      taken[r, c] := FALSE
    END
  END;
  taken[1, 4] := TRUE;
  taken[1, 5] := TRUE;
  taken[3, 2] := TRUE;
  taken[4][8] := TRUE;

  free := 0;
  FOR r := 1 TO Rows DO
    WriteCard(r, 2);
    WriteString("  ");
    FOR c := 1 TO Cols DO
      IF taken[r, c] THEN
        Write('X')
      ELSE
        Write('.');
        INC(free)
      END
    END;
    WriteLn
  END;
  WriteString("Free seats: ");
  WriteCard(free, 0);
  WriteLn
END seats.

taken records which seats of a small hall are sold. The outer loop goes through the rows and the inner loop through the seats of a row. taken[4][8] is another way to write taken[4, 8].

$ gm2 seats.mod -o seats
$ ./seats
 1  ...XX...
 2  ........
 3  .X......
 4  .......X
Free seats: 28

Arrays of arrays

ARRAY [1..3], [1..5] OF T is short for ARRAY [1..3] OF ARRAY [1..5] OF T. Each row is an array of its own, so it can be assigned as a whole or passed to a procedure.

rows.mod
MODULE rows;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

CONST
  Weeks = 3;
  Days = 5;

TYPE
  Week = ARRAY [1..Days] OF CARDINAL;

VAR
  visits: ARRAY [1..Weeks] OF Week;
  w, d: CARDINAL;

PROCEDURE WeekTotal(days: Week): CARDINAL;
VAR
  i, sum: CARDINAL;
BEGIN
  sum := 0;
  FOR i := 1 TO Days DO
    sum := sum + days[i]
  END;
  RETURN sum
END WeekTotal;

BEGIN
  FOR d := 1 TO Days DO
    visits[1][d] := 10 + d
  END;
  visits[2] := visits[1];
  visits[2, 5] := 40;
  visits[3] := visits[2];
  visits[3, 1] := 0;
  FOR w := 1 TO Weeks DO
    WriteString("Week ");
    WriteCard(w, 0);
    WriteString(":");
    FOR d := 1 TO Days DO
      WriteCard(visits[w, d], 4)
    END;
    WriteString("  total");
    WriteCard(WeekTotal(visits[w]), 4);
    WriteLn
  END
END rows.

The element type of visits is the named type Week. visits[2] := visits[1] copies a whole row, and WeekTotal(visits[w]) passes one row as a Week. Single elements are selected with two indexes, in either form.

$ gm2 rows.mod -o rows
$ ./rows
Week 1:  11  12  13  14  15  total  65
Week 2:  11  12  13  14  40  total  90
Week 3:   0  12  13  14  40  total  79

Character arrays

Modula-2 has no separate string type. A string is kept in an array of characters, and a string constant can be assigned to such an array if it fits. When the string is shorter than the array, the character 0C marks its end.

letters.mod
MODULE letters;

FROM InOut IMPORT WriteString, WriteLn, WriteCard, Write;

VAR
  city: ARRAY [0..15] OF CHAR;
  i: CARDINAL;

BEGIN
  city := "Zurich";
  WriteString(city);
  WriteLn;
  i := 0;
  WHILE city[i] # 0C DO
    Write(CAP(city[i]));
    Write(' ');
    INC(i)
  END;
  WriteLn;
  WriteCard(i, 0);
  WriteString(" letters in an array of ");
  WriteCard(SIZE(city), 0);
  WriteString(" characters");
  WriteLn
END letters.

WriteString prints the characters up to the terminating 0C. The WHILE loop indexes the array like any other and stops at the terminator. SIZE gives the size of the whole array, of which the six letters use only a part. The strings article covers the string procedures of the library.

$ gm2 letters.mod -o letters
$ ./letters
Zurich
Z U R I C H 
6 letters in an array of 16 characters

The sieve of Eratosthenes

The sieve finds the primes up to a limit by crossing out the multiples of each prime. An array of booleans indexed by the numbers themselves records which numbers are still candidates.

sieve.mod
MODULE sieve;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

CONST
  Limit = 100;

VAR
  prime: ARRAY [2..Limit] OF BOOLEAN;
  n, multiple, count: CARDINAL;

BEGIN
  FOR n := 2 TO Limit DO
    prime[n] := TRUE
  END;
  n := 2;
  WHILE n * n <= Limit DO
    IF prime[n] THEN
      multiple := n * n;
      WHILE multiple <= Limit DO
        prime[multiple] := FALSE;
        INC(multiple, n)
      END
    END;
    INC(n)
  END;

  count := 0;
  FOR n := 2 TO Limit DO
    IF prime[n] THEN
      WriteCard(n, 4);
      INC(count);
      IF count MOD 10 = 0 THEN
        WriteLn
      END
    END
  END;
  WriteLn;
  WriteCard(count, 0);
  WriteString(" primes up to ");
  WriteCard(Limit, 0);
  WriteLn
END sieve.

The index range [2..Limit] starts at 2, the first prime, so prime[n] answers the question for n directly. For each prime the inner loop crosses out its multiples, starting at its square, because smaller multiples were crossed out by smaller primes. The second part prints the numbers that are left, ten to a line.

$ gm2 sieve.mod -o sieve
$ ./sieve
   2   3   5   7  11  13  17  19  23  29
  31  37  41  43  47  53  59  61  67  71
  73  79  83  89  97
25 primes up to 100

Next steps

The procedures of this article accept arrays of one fixed type only. The open arrays article writes procedures that accept arrays of any length.

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have declared Modula-2 arrays with different index types, assigned and compared them, passed them to procedures, checked their bounds, built tables from arrays of arrays, and stored text in character arrays. The procedures article covers the value and VAR parameters used here, and the loops article the loops that walk through the arrays.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.