Learning about Arrays


Simple Sorting


This set of programs introduces a new kind of variable - - the array
An array is a list of variables whose names differ only by having a
different number as part of them.
This is mildly useful because we can use one var statement to create a
large number of storage locations.
This is blindingly useful because by changing the number in the
variable name we can change the name of the variable that we are
talking about dynamically -- that is, while the program runs.
This lets us use the same loop to handle a great number of different
storage locations.

In the first example I don't use array variables at all. You should find
it pretty easy to understand. Suppose that you wanted to expand it to
five animals? Ten animals? One hundred animals? You can see how
tedious and error prone this would get. Stay tuned for the next


Ok, This is the same as the previous example except that it uses array
variables. Note that instead of three READLN statements there is now
only one but it is done three times because it is inside of a FOR loop. I
haven't used a loop for the WRITELN because getting the right
numbers in the [] square brackets requires the knowledge of a special
mathematical trick (although it can be done) I'm not asking you to do
it -- but can you see why you need a trick?


Here we are back to not using arrays but with a different task --
sorting. As you might guess, sorting is something that computers do a
lot of so understanding what is happening is worth your attention. Can
you understand this program? This is not easy -- try some sample
values for the three variables and see if you can go through the
program step by step.


This example is an extra version of the one above. I haven't changed
anything about how it works. I have just written the code that
switches the values as a procedure. This saves me from writing the
code three times. Note how the procedure transposes the values that I
pass it.


Here we go again with arrays. This is the same sort program that we
did in the previous example but using array variables. At first the
names of the variables like "nums[counter + 1]" will seem very
strange. You may also wonder about the FOR loop inside of a FOR loop.
It works but why did I do it. The answer is so that I can sort more
than three numbers. See the next example.


Ok, this is the whole thing -- it sorts any number of numbers.


When I looked back at this code I wondered if I had just repeated the
previous example. But I hadn't. The change is the introduction of the
variable "notsorted." This lets the short end when all the numbers are
in order without going completely through the list like the previously
one did. On a large list that is partially ordered this can be a real time

Rules for writing Pascal statements

General Index to Sample Programs

[ Home ][ Vita ][ Copyright  ][ Copyright  ]