Tuesday, 28 August 2012

Pascal Programming Lesson #7 - Arrays


Arrays are variables that are made up of many variables of the same data type but have only one name. Here is a visual representation of an array with 5 elements:

1value 1
2value 2
3value 3
4value 4
5value 5

Arrays are declared in almost the same way as normal variables are declared except that you have to say how many elements you want in the array.

program Arrays;

var
   a: array[1..5] of Integer;

begin
end.


We access each of the elements using the number of the elements behind it in square brackets.

program Arrays;

var
   a: array[1..5] of Integer;

begin
   a[1] := 12;
   a[2] := 23;
   a[3] := 34;
   a[4] := 45;
   a[5] := 56;
end.


It is a lot easier when you use a loop to access the values in an array. Here is an example of reading in 5 values into an array:

program Arrays;

var
   a: array[1..5] of Integer;
   i: Integer;

begin
   for i := 1 to 5 do
      Readln(a[i]);
end.

Sorting arrays

You will sometimes want to sort the values in an array in a certain order. To do this you can use a bubble sort. A bubble sort is only one of many ways to sort an array. With a bubble sort the biggest numbers are moved to the end of the array.
You will need 2 loops. One to go through each number and another to point to the other number that is being compared. If the number is greater then it is swapped with the other one. You will need to use a temporary variable to store values while you are swapping them.

program Arrays;

var
   a: array[1..5] of Integer;
   i, j, tmp: Integer;

begin
   a[1] := 23;
   a[2] := 45;
   a[3] := 12;
   a[4] := 56;
   a[5] := 34;

   for i := 1 to 4 do
      for j := i + 1 to 5 do
         if a[i] > a[j] then
         begin
            tmp := a[i];
            a[i] := a[j];
            a[j] := tmp;
         end;

   for i := 1 to 5 do
      writeln(i,': ',a[i]);
end.

2D arrays

Arrays can have 2 dimensions instead of just one. In other words they can have rows and columns instead of just rows.

 123
1123
2456
3789

Here is how to declare a 2D array:

program Arrays;

var
   a: array [1..3,1..3] of Integer;

begin
end.


To access the values of a 2d array you must use 2 numbers in the square brackets. 2D arrays also require 2 loops instead of just one.

program Arrays;

var
   r, c: Integer;
   a: array [1..3,1..3] of Integer;

begin
   for r := 1 to 3 do
      for c := 1 to 3 do
         Readln(a[r,c]);
end.


You can get multi-dimensional arrays that have more than 2 dimensions but these are not used very often so you don't need to worry about them.

0 comments:

Post a Comment