Advertise here.

Tuesday 28 August 2012

Pascal Programming Lesson #8 - Types, Records and Sets


Types

It is possible to create your own variable types using the type statement. The first type you can make is records. Records are 2 or more variables of different types in one. An example of how this could be used is for a student who has a student number and a name. Here is how you create a type:

program Types;

Type
   Student = Record
      Number: Integer;
      Name: String;
   end;

begin
end.

After you have created the type you must declare a variable of that type to be able to use it.

program Types;

Type
   StudentRecord = Record
      Number: Integer;
      Name: String;
   end;

var
   Student: StudentRecord;

begin
end.

To access the Number and Name parts of the record you must do the following:

program Types;

Type
   StudentRecord = Record
      Number: Integer;
      Name: String;
   end;

var
   Student: StudentRecord;

begin
   Student.Number := 12345;
   Student.Name := 'John Smith';
end.

The other type is a set. Sets are not very useful and anything you can do with a set can be done just as easily in another way. The following is an example of a set called Animal which has dog, cat and rabbit as the data it can store:

program Types;

Type
   Animal = set of (dog, cat, rabbit);

var
   MyPet: Animal;

begin
   MyPet := dog;
end.
You can't use Readln or Writeln on sets so the above way of using it is not very useful. You can create a range of values as a set such as 'a' to 'z'. This type of set can be used to test if a value is in that range.

program Types;

uses
   crt;

Type
   Alpha = 'a'..'z';

var
   Letter: set of Alpha;
   c: Char;

begin
   c := ReadKey;
   if c in [Letter] then
      Writeln('You entered a letter');
end.

0 comments:

Post a Comment