home account info subscribe login search My ITKnowledge FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Learn Pascal in a Three Days (2nd Ed.)
(Publisher: Wordware Publishing, Inc.)
Author(s):
ISBN: 1556225679
Publication Date: 07/01/97

Bookmark It

Search this book:
 
Previous Table of Contents Next


Declaration of Arrays in the TYPE Section

It is preferable that array declarations be associated with the TYPE statement, as in this example:

    TYPE>
     AnArray = ARRAY[1..6] OF INTEGER;
    VAR
     MyArray:AnArray;

In this case you can declare more than one array of the type “AnArray” in the VAR section:

    VAR
     YourArray, MyArray:AnArray;

It is also possible to use a previously declared subrange as an index range for an array, like this:

    TYPE
     MyRange = 1..6;
     AnArray = ARRAY[MyRange] OF INTEGER;
    VAR
     MyArray:AnArray;

Although we have started our arrays from the index “1,” there is no obligation to do so. The index range can be any valid subrange, but you must always remember not to exceed the defined index range.

Example: Sorting an Array

If you would like to sort some numbers (or names), the best way is to store them in an array, then use one of the sorting algorithms. A simple way (but not the most efficient) to sort numbers in an ascending order is known as the “bubble sort.” The algorithm is as follows:

1.  Compare the first element to the second one. If the first element is greater, swap them.
2.  Repeat the comparison between the first element and each of the rest of the array elements. If it is greater than any element, swap them.
3.  By the end of these comparisons the first element will be the smallest in the array.
4.  Repeat the previous steps for the second element, the third, and so on until the next-to-last element.

After this process is completed, the array will be sorted in an ascending order. This algorithm is demonstrated in the following program. The comparisons need two nested loops. The outer loop (index “I”) starts from the first element (I=1) and ends before the last element (I=ArraySize-1). The inner loop (index “J”) starts one step after the start of the outer loop (J=I+1) and goes all the way to the last element (J=ArraySize).

{ -------------------- figure 5-5 -------------------- }
PROGRAM Sorting(INPUT,OUTPUT);
CONST
 ArraySize = 6;
TYPE
 Range = 1..ArraySize;
 NumbersArray = ARRAY[Range] OF INTEGER;
VAR
 Numbers :NumbersArray;
 I, J, Pot:INTEGER;
BEGIN
{ Read the array }
{ ---------- }
  FOR I:= 1 TO ArraySize DO
   BEGIN
    WRITE('Enter element #', I,': ');
    READLN(Numbers[I])
   END;
{ Sort the array }
{ --------- }
  FOR I:= 1 TO ArraySize-1 DO                { outer loop }
   BEGIN                          { optional block }
    FOR J:= I+1 TO ArraySize DO              { inner loop }
     BEGIN
      IF Numbers[I] > Numbers[J] THEN
        BEGIN                     { swap contents }
         Pot:= Numbers[J];
         Numbers[J]:= Numbers[I];
         Numbers[I]:= Pot
        END
     END                 { end of inner loop }
   END;                  { end of outer loop }
{ Display Results }
{ ---------- }
  WRITELN;
  WRITELN('The sorted array is:');
  FOR I:= 1 TO ArraySize DO
   WRITELN(Numbers[I]);
  WRITELN('Press ENTER to continue..');
  READLN
END.

A sample run is as follows:

Enter element #1: 6
Enter element #2: 33
Enter element #3: 4
Enter element #4: 2
Enter element #5: 55
Enter element #6: 9

The sorted array is:
2
4
6
9
33
55
Press ENTER to continue..

Swapping the contents of two elements is done by using a third variable (Pot) to hold the contents of one variable temporarily, thus:

    Pot:= Numbers[J];
    Numbers[J]:= Numbers[I];
    Numbers[I]:= Pot

This process is similar to swapping the contents of two cups, one of which contains coffee and the other tea; all you need is an empty cup (Pot).

To have the array sorted in a descending order, just reverse the “greater than” process to “less than.”

Drill 5-4

Modify your program from drill 5-3 to display the best score and the number of the highest scoring student in the class. The output should look like this:

    Student #       Score
    -----------------
     1          70.00
     2          88.00
     3          67.00
     4          90.00
     5          86.00
    -----------------
    Average score = 80.20
    The best score = 90.00
    The best of the class is student #4

You may use the following algorithm to obtain the highest number in the array of scores:

1.  Store the score of the first student in a variable such as “BestScore,” and the index of that student in a variable “BestOfClass.”
2.  Starting from the second element in the array of scores, and continuing all the way to the end, repeat the following comparison.
3.  If any number is greater than “BestScore,” store it in “BestScore” and store its index in “BestOfClass.”
4.  By the end of the loop, the variable “BestScore” will contain the highest score, and the corresponding student number will be stored in “BestOfClass.”

5-5 Two-Dimensional Arrays

To declare a two-dimensional array, use the form:

    VAR
    array-name: ARRAY[index-range-1, index-range-2]
                               OF element-type;

You may also declare it in the type section as follows:

    TYPE
    type-name = ARRAY[index-range-1, index-range-2]
                               OF element-type;

where “index-range1” and “index-range2” are the ranges of the first and second dimensions.

Look at this declaration:

    TYPE
      Score = ARRAY[1..100, 1..6] OF INTEGER;

This statement declares an array “Score,” which can store the scores of 100 students in six different classes; generally speaking, it can store up to 600 integers. As you can see, each dimension is represented by a subrange.

You can also declare a multidimensional array of any number of dimensions using the general form:

    TYPE
    type-name = ARRAY[index-range-1, index-range-2,
             ..., index-range-n] OF element-type;

In most applications, however, you will not need more than two dimensions.


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.