Sign Guestbook
View Guestbook
Invite Your Friends
Website Awards
Message Forum
Source Codes
Downloads
Links
About Me
 
     
Lesson 1 - The first few steps in Pascal Programming
Lesson 2 - Variables, Constants and the Assignment  Statement
Lesson 3 - Special Functions: ClrScr(), GotoXy(), etc...
Lesson 4 - Program Control
Lesson 5 - The CASE-OF Statement
Lesson 6 - Logical Operators and Boolean Expressions
Lesson 7 - Procedures and Functions
Lesson 8 - BGI Graphics
Lesson 9 - File Handling
Lesson 10 - Arrays
Lesson 11 - Record Data Structure
Lesson 12 - Strings

Add this site to your Favourites

   



 


Lesson 10
- Arrays

 

This lesson will cover:

 

 

 

What are Arrays?

An Array is a powerful data structure that stores variable data having the same data type. It is just like a small fixed number of boxes linked together one after the other storing things that are related to each other. An array is said to be a static data structure because, once declared, its original size that is specified by the programmer will remain the same throughout the whole program and cannot be changed.

Up until now, we have used single variables only as a tool to store data. Now we will be using the array data structure and here is how it is declared:

Var

myArray : Array[1..20] of Integer;

<arrayName> : Array[n..m] of <Data Type>;

An array data structure defines the size of the array and the data type that it will use for storing data. In the above example, the array stores up to 20 integers however I may have used 30 integers or more. This size depends on your program requirements.

Arrays are used just like ordinary variables. They are used to store typed data just like the ordinary variables. You will now learn how to assign data to arrays and read data from arrays.

In the example above, I have declared 20 integers and I should be able to access each and one of them and here is how I do it.

To assign values to a particular integer of an array, we do it like this:

myArray[5] := 10;
myArray[1] := 25;

<arrayName>[index] := <relevant data>


You just take the array in subject, specify the index of the variable of the array and assign it a value relevant to the data type of the array itself.

Reading a value from an array is done as follows:

Var
    myVar   : Integer;
    myArray : Array[1..5] of Integer;

Begin
 myArray[2] := 25;
 myVar := myArray[2];
End.

Just like ordinary variables, arrays should be initialised, otherwise scrap data will remain stored in them. If we want to intialise 2 whole 20-sized integer and boolean arrays to 0 and false respectively, we do it like this:

Var
    i           : Integer;
    myIntArray  : Array[1..20] of Integer;
    myBoolArray : Array[1..20] of Boolean;

Begin
 For i := 1 to 20 do
  Begin
   myIntArray[i]  := 0;
   myBoolArray[i] := false;
  End;
End.

Introducing User-Defined Data Types

Now that we have used various built-in data types, we have arrived at a point were we want to use our defined data types. Built-in data types are the ones we used lately, such as Integer, Boolean and String. Now we will learn how to specify our own customised data types and this is just how it is done:

Type

<myDataType> = <particularDataType>;

The "Type" keyword is a reserved Pascal word used to define our own data types. So you start defining your own data types by using this keyword. After defining your own data types, you may start using them just like the other built-in data types as follows:

Var

<myVar> : <myDataType>;

Now lets define a new simple data type and note how it will be used in the program below:

Type
    nameType = String[50];
    ageType  = 0..150; { age range: from 0 to 150 }

Var
    name : nameType;
    age  : ageType;

Begin
 Write('Enter your name: ');
 Readln(name);
 Write('Enter your age: ');
 Readln(age);
 Writeln;
 Writeln('Your name:', name);
 Writeln('Your age :', age);
 Readln;
End.

In the above example we defined a String[50] and a 0..150 data type. The nameType only stores strings up to 50 characters long and the ageType stores numbers only from 0 to 150.

We can define more complex user-defined data types. Here is an example of more complex user-defined data types:

Type
    i               = 1..5;
    myArrayDataType = Array[1..5] of Byte;
    byteFile        = File of Byte; { binary file }        

Var
    myArrayVar : myArrayDataType;
    myFile     : byteFile;

Begin
 Writeln('Please enter 5 number from (0..255): ');
 For i := 1 to 5 do
  Readln(myArrayVar[i]);
 Writeln('You have entered the following numbers: ');
 For i := 1 to 5 do
  Writeln('Number ',i,': ',myArrayVar[i]);

 Writeln('Now writing them to file...');
 {store the numbers in a file}
 Assign(myFile, 'example.dat');
 ReWrite(byteFile);
 Write(myFile, myArrayVar[i]);
 Close(myFile);
 Writeln('Done, you may exit..');
 Readln;
End.

In the above example I showed you how to incorporate arrays as user-defined data types. Note that you may use user-defined data types more than once.

2 Dimensional and Multi-Dimensional Arrays

2 Dimensional arrays and multi-dimensional are arrays which store variables in a second or nth dimension having n*m storage locations. Mutli dimensional arrays including the 2 dimensional array, are declared by using multiple square brackets placed near each other or using commas with one sqaure brackets as an alternative. Here is how multi-dimensional are declared:

my2DArray       : Array[i..j][k..l] of <DataType>;
myMultiDimArray : Array[m..n][o..p][q..r][s..t]... of <DataType>; 

Let us have the 2 dimensional array defined first. Think of a grid where each box is located by using horizontal and vertical coordinates just in the example below:

1 2 3 4 5
2        
3     3,4  
4        
5   5,3    

An example of a 5 by 5 2D array illustrated on a grid

Let us declare an array having 3 by 5 dimensions, assign a value to a particular variable in the array and illustrate this on a grid just like the one above:

Var
my2DArray : Array[1..3][1..5] of Byte;
Begin
 my2DArray[2][4] := 10;
End.

Having the vertical axis as the 1st dimension and the horizontal one as the 2nd dimension, the above example is illustrated as follows:

1 2 3 4 5
2    
10
 
3        

Multi-dimensional arrays are rare and are not important. The single and 2D dimensional arrays are the 2 most frequent dimensions.

The following example is a bit more complex example than the previous examples and it also uses a 2 dimensional array to illustrate their use.

Uses Crt;
Type
   myRange      = 1..5;
   arrayIntType = Array[myRange] of Integer;
   myFileType   = File of arrayIntType;
Var
   i        : myRange;
   myFile   : myFileType;
   { the next array is 2 dimensional }
   arrayInt : Array[1..2] of arrayIntType; 
Begin
 Clrscr;
 Randomize;
 For i := 1 to 5 do
  Begin
   arrayInt[1][i] := Random(1000);
   Writeln('rand num: ',arrayInt[1][i]);
  End;
 Assign(myFile, 'test.dat');
 ReWrite(myFile);
 Write(myFile, arrayInt[1]);
 Close(myFile);
 ReSet(myFile);
 Read(myFile, arrayInt[2]);
 Close(myFile);

 For i := 1 to 5 do
  Writeln(i,': ', arrayInt[2][i]);
 Readln;
End.

This concludes the arrays lesson. In the next lesson we will learn about Record data structures, their uses and we will also learn how to use binary files used record data structures.

 
 


User Comments

Post By: strmckr Posted On: 2009-11-03
William: turbo pascal or older does not allow dynamic arrays they are static. how ever if you are using free pascal you can: i suggest reading this: http://www.freepascal.org/docs-html/ref/refsu14.html

Post By: William Posted On: 2009-09-26
I have a question about the arrays, can you set the limit of an array to a variable, meaning that the size of the array is dependent upon a users input. E.g. var limit : integer; myArray : Array[1..limit] of Integer; would this work???

Post By: tafadzwa paul maskiri chisarur Posted On: 2009-09-25
this is very educative. you provide alot of insight

Post By: stef Posted On: 2009-05-28
nice stuff

Post By: Muhedin Abdullahi Mohamed Posted On: 2009-05-16
this is really a usefull site, but I see it may be better to organise the lessons more than it is; for example giving a detailed explanation about a particular structure of the language followed by a number of examples increasing in default the simplest one first,then the second simplest......and lastly the most deficult one.....that is my poor point of view.

Post By: asitya Posted On: 2009-05-13
thak u for makin this site. it has help us in our study. than u.

Post By: Rafid Posted On: 2009-04-15
i want see array multiplcation/reading column one by one&rows also.Thank you.

Post By: Andrej Posted On: 2008-12-10
Hello. You've got a typo in lesson "Introducing User-Defined Data Types". The second program, line #18: ReWrite(byteFile); It should read: ReWrite (myFile); Also you have defined a type 'i' without a variable 'i' on line #2. Thanx for the tutorials :)

Post By: mohammad Posted On: 2008-11-28
Your Comment

Post By: nelly Posted On: 2008-08-26
compare and contrast data types,data structures,compiling,coding,debugging,testing and execution in structured visual language and 4gland pascal language. thanks

Post By: lennox Posted On: 2008-08-26
fantastic

Post By: Trust Posted On: 2008-07-30
Valued website.

Post By: SHARON Posted On: 2008-06-18
i have a big problem in undertanding arrays datafiles and text files please help and if possible send me coded examples

Post By: Roin Posted On: 2008-06-10
This is great. You are good, this is the best tutorial for Pascal avaiable in the internet

Post By: Camro Posted On: 2008-03-24
With the graphs, wouldnt there be a white box for 1,1? the top left corner should be a 0

Post By: John Posted On: 2008-03-18
Hi I have a doubt concerning the use of arrays in Pascal. 1. var a : array[1..10]of real procedure arb (b:array[1..10] of real); { random procedure } arb (a); {Is this a pass by value ?} 2. var a, b : array [1..5] of integer; a:=b; { Does this take the place of a for loop ? or does it go deeper ? I read in one site that it replaces the for loop assigning and another site said if I do b[3]:=5, after this step then a[3] is also equal to 5. } Can you help me out with this please? Thanks.

Post By: Posted On: 2008-03-10
i have an assignment to create a magic square and i don't have a clue waht to do. PLz HELP

Post By: what if your array wi Posted On: 2008-02-05
what if your array will be both string and integer??? (please answer my question!!!)

Post By: D0u5 Posted On: 2008-01-21
nice tutorial...

Post By: Do$$e Posted On: 2007-10-29
VERY GOOD!!!!

Post By: cinderella Posted On: 2007-10-29
this is nyce stuff thanks a lost

Post By: moderator Posted On: 2006-10-11
Sorting tutorial is now discussed in the articles section. Click here for the sorting article.

Post By: wellington Posted On: 2006-08-29
can you include the concept of sorting in your tutorial. otherwise the rest is occur. thank you very much for interest of helping people such as us, we greatly apreciate what you are doing


Post Your Comment on this Article!
Your Name/Nickname:
Your Email:
Your Comment:
Insert the BLUE numbers shown below in the text field on the right. [ This is an anti-spam counter-measure ]
284311655184
 
 
[HOME][LESSON INDEX][INVITE A FRIEND][FORUM][ABOUT ME]

modified last: September 2005 (Article Version: 2)

mail to: victorsaliba@hotmail.com

© Victor John Saliba 2006  
| Privacy Statement | Disclaimer | Contact Us |
 
 
 
www.pascalprogramming.byethost15.com © Victor John Saliba 2006