next up previous contents
Next: Homework Assignment (200 points) Up: Common Array Techniques Previous: Common Array Techniques   Contents

Going Through an Array

One of the strengths of arrays (as compared to individual variables) is that it is easy to access individual elements of an array. If we have variables num01, num02 and etc. up to num50 (a total of 50 individual variables), the initialization of all 50 variables will be tedious because it requires 50 assignment statements.

However, if we use an array of 50 integers, however, the initialization of all 50 integers is easy. Observe the following code:

var
  nums : array [0..49] of integer;
  i : integer;
begin
  i := 0;
  while (i < 50) do
    begin
      nums[i] := 0;
      i := i + 1
    end
end.

This program with only three lines of code initializes all 50 integers in array nums to zero. In fact, this code can initialize elements in nums to 0, regardless of the number of items in the array. All we need to do is to change the bound.

If we want this program to be easy to maintain, with respect to the number of items in the array, we can define a constant. The following program utilizes a constant for the size of the array:

const
  nums_size = 50;
var
  nums : array [0..nums_size-1] of integer;
  i : integer;
begin
  i := 0;
  while (i < nums_size) do
    begin
      nums[i] := 0;
      i := i + 1
    end
end.

Note how the definition of nums_size uses a equal sign (and not a colon). This is because this is a definition of a constant, and we are equating the symbolic name nums_size with the value 50.

By simply changing the definition of nums_size, we can change the size of the array without having to alter any other line in the program.


next up previous contents
Next: Homework Assignment (200 points) Up: Common Array Techniques Previous: Common Array Techniques   Contents
Tak Auyeung 2003-12-03