Wednesday, 2 February 2011

Pascal Lesson 12 - Units

Learn Pascal Programming Tutorial Lesson 12 - Units

We already know that units, such as the crt unit, let you use more procedures and functions than the built-in ones. You can make your own units which have procedures and functions that you have made in them.
To make a unit you need to create new Pascal file which we will call MyUnit.pas. The first line of the file should start with the unit keyword followed by the unit's name. The unit's name and the unit's file name must be exactly the same.
unit MyUnit;
The next line is the interface keyword. After this you must put the names of the procedures that will be made available to the program that will use your unit. For this example we will be making a function called NewReadln which is like Readln but it lets you limit the amount of characters that can be entered.
unit MyUnit;

interface

function NewReadln(Max: Integer): String;

The next line is implementation. This is where you will type the full code for the procedures and functions. We will also need to use the crt unit to make NewReadln. We end the unit just like a normal program with the end keyword.
unit MyUnit;

interface

function NewReadln(Max: Integer): String;

implementation

function NewReadln(Max: Integer): String;
var
   s: String;
   c: Char;
begin
   s := '';
   repeat
      c := ReadKey;
      if (c = #8){#8 = BACKSPACE} and (s <> '') then
         begin
            Write(#8+' '+#8);
            delete(s,length(s),1);
         end;
      if (c <> #8) and (c <> #13){#13 = ENTER} and (length(s) < Max) then
         begin
            Write(c);
            s := s + c;
         end;
   until c = #13;
   NewReadln := s;
end;

end.

Once you have saved the unit you must compile it. Now we must make the program that uses the unit that we have just made. This time we will type MyUnit in the uses section and then use the NewReadln function.
program MyProgram;

uses
   MyUnit;

var
   s: String;

begin
   s := NewReadln(10);
end.

Pascal Lesson 11 - Data Files

Learn Pascal Programming Tutorial Lesson 11 - Data Files

Data files are different from text files in a few ways. Data files are random access which means you don't have to read through them line after line but instead access any part of the file at any time. Here is how you declare a data file:
program DataFiles;

var
   f: file of Byte;

begin
end.

We then use Assign in the same way as we do with a text file.
program DataFiles;

var
   f: file of Byte;

begin
   Assign(f,'MyFile.dat');
end.

You can use Rewrite to create a new file or overwrite an existing one. The difference between text files and data files when using Rewrite is that data files can be read and written to.
program DataFiles;

var
   f: file of Byte;

begin
   Assign(f,'MyFile.dat');
   Rewrite(f);
end.

Reset is the same as Rewrite except that it doesn't overwrite the file.
program DataFiles;

var
   f: file of Byte;

begin
   Assign(f,'MyFile.dat');
   Reset(f);
end.

When you write to a file using the Write command you must first put the value to be written to the file into a variable. Before you can write to or read from a data file you must use the Seek command to find the right place to start writing. You must also remember that data files start from position 0 and not 1.
program DataFiles;

var
   f: file of Byte;
   b: Byte;

begin
   Assign(f,'MyFile.dat');
   Reset(f);
   b := 1;
   Seek(f,0);
   Write(f,b);
end.

The Read command is used to read from a data file.
program DataFiles;

var
   f: file of Byte;
   b: Byte;

begin
   Assign(f,'MyFile.dat');
   Reset(f);
   Seek(f,0);
   Read(f,b);
end.

You must close a data file when you are finished with it just like with text files.
program DataFiles;

var
   f: file of Byte;
   b: Byte;

begin
   Assign(f,'MyFile.dat');
   Reset(f);
   Seek(f,0);
   Read(f,b);
   Close(f);
end.

The FileSize command can be used with the FilePos command to find out when you have reached the end of the file. FileSize returns the actual number of records which means it starts at 1 and not 0. The FilePos command will tell at what position in the file you are.
program DataFiles;

var
   f: file of Byte;
   b: Byte;

begin
   Assign(f,'MyFile.dat');
   Reset(f);
   while FilePos(f) <> FileSize(f) do
      begin
         Read(f,b);
         Writeln(b);
      end;
   Close(f);
end.

The Truncate command will delete everything in the file from the current position.
program DataFiles;

var
   f: file of Byte;

begin
   Assign(f,'MyFile.dat');
   Reset(f);
   Seek(f,3);
   Truncate(f);
   Close(f);
end.

One of the most useful things about data files is that you can use them to store records.
program DataFiles;

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

var
   Student: StudentRecord;
   f: file of StudentRecord;

begin
   Assign(f,'MyFile.dat');
   Rewrite(f);
   Student.Number := 12345;
   Student.Name := 'John Smith';
   Write(f,Student);
   Close(f);
end.

Pascal Lesson 10 - Text Files

Learn Pascal Programming Tutorial Lesson 10 - Text Files

You should by now know that a text file is a file with lines of text. When you want to access a file in Pascal you have to first create a file variable.
program Files;

var
   f: Text;

begin
end.

After the variable has been declared you must assign the file name to it.
program Files;

var
   f: Text;

begin
   Assign(f,'MyFile.txt');
end.

To create a new empty file we use the Rewrite command. This will overwrite any files that exist with the same name.
program Files;

var
   f: Text;

begin
   Assign(f,'MyFile.txt');
   Rewrite(f);
end.

The Write and Writeln commands work on files in the same way they work on the screen except that you must use an extra parameter to tell it to write to the file.
program Files;

var
   f: Text;

begin
   Assign(f,'MyFile.txt');
   Rewrite(f);
   Writeln(f,'A line of text');
end.

If you want to read from a file that already exists then you must use Reset instead of Rewrite. Use Readln to read lines of text from the file. You will also need a while loop that repeats until it comes to the end of the file.
program Files;

var
   f: Text;
   s: String;

begin
   Assign(f,'MyFile.txt');
   Reset(f);
   while not eof(f) do
      Readln(f,s);
end.

Append opens a file and lets you add more text at the end of the file.
program Files;

var
   f: Text;
   s: String;

begin
   Assign(f,'MyFile.txt');
   Append(f);
   Writeln(f,'Some more text');
end.

No matter which one of the 3 access types you choose, you must still close a file when you are finished using it. If you don't close it then some of the text that was written to it might be lost.
program Files;

var
   f: Text;
   s: String;

begin
   Assign(f,'MyFile.txt');
   Append(f);
   Writeln(f,'Some more text');
   Close(f);
end.

You can change a file's name with the Rename command and you can delete a file with the Erase command.
program Files;

var
   f: Text;

begin
   Assign(f,'MyFile.txt');
   Rename(f,'YourFile.txt');
   Erase(f);
   Close(f);
end.

To find out if a file exists, you must first turn off error checking using the {$I-} compiler directive. After that you must Reset the file and if IOResult = 2 then the file was not found. If IOResult = 0 then the file was found but if it is any other value then the program must be ended with the Halt command. IOResult loses its value once it has been used so we also have to put that into another variable before using it. You must also use {$I+} to turn error checking back on.
program Files;

var
   f: Text;
   IOR: Integer;

begin
   Assign(f,'MyFile.txt');
{$I-}
   Reset(f);
{$I+}
   IOR := IOResult;
   if IOR = 2 then
      Writeln('File not found');
   else
      if IOR <> 0 then
         Halt;
   Close(f);
end.

Pascal Lesson 9 - Procedures and Functions

Learn Pascal Programming Tutorial Lesson 9 - Procedures and Functions

Procedures

Procedures are sub-programs that can be called from the main part of the program. Procedures are declared outside of the main program body using the procedure keyword. Procedures must also be given a unique name. Procedures have their own begin and end. Here is an example of how to make a procedure called Hello that prints "Hello" on the screen.
program Procedures;

procedure Hello;
begin
   Writeln('Hello');
end;

begin
end.

To use a procedure we must call it by using its name in the main body.
program Procedures;

procedure Hello;
begin
   Writeln('Hello');
end;

begin
   Hello;
end.

Procedures must always be above where they are called from. Here is an example of a procedure that calls another procedure.
program Procedures;

procedure Hello;
begin
   Writeln('Hello');
end;

procedure HelloCall;
begin
   Hello;
end;

begin
   HelloCall;
end.

Procedures can have parameters just like the other commands we have been using. Each parameter is given a name and type and is then used just like any other variable. If you want to use more than one parameter then they must be separated with semi-colons.
program Procedures;

procedure Print(s: String; i: Integer);
begin
   Writeln(s);
   Writeln(i);
end;

begin
   Print('Hello',3);
end.

Global and Local variables

The variables we have been using so far have been global because they can be used at any time during the program. Local variables can only be used inside procedures but the memory they use is released when the procedure is not being used. Local variables are declared just underneath the procedure name declaration.
program Procedures;

procedure Print(s: String);
var
   i: Integer;
begin
   for i := 1 to 3 do
      Writeln(s);
end;

begin
   Print('Hello');
end.

Functions

Functions are like procedures except they return a value. The function keyword is used instead of procedure when declaring a function. To say what data type the return value must be you must use a colon and the name of the type after the function's name.
program Functions;

function Add(i, j:Integer): Integer;
begin
end;

begin
end.

Assigning the value of a function to a variable make the variable equal to the return value. If you use a function in something like Writeln it will print the return value. To set the return value just make the name of the function equal to the value you want to return.
program Functions;

var
   Answer: Integer;

function Add(i, j:Integer): Integer;
begin
   Add := i + j;
end;

begin
   Answer := Add(1,2);
   Writeln(Add(1,2));
end.

You can exit a procedure or function at any time by using the Exit command.
program Procedures;

procedure GetName;
var
   Name: String;
begin
   Writeln('What is your name?');
   Readln(Name);
   if Name = '' then
      Exit;
   Writeln('Your name is ',Name);
end;

begin
   GetName;
end.

Pascal Lesson 8 - Types, Records and Sets

Learn Pascal Programming Tutorial 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.

Pascal Lesson 7 - Arrays

Learn Pascal Programming Tutorial 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.

Pascal Lesson 6 - Loops

Learn Pascal Programming Tutorial Lesson 6 - Loops

Loops are used when you want to repeat code a lot of times. For example, if you wanted to print "Hello" on the screen 10 times you would need 10 Writeln commands. You could do the same thing by putting 1 Writeln command inside a loop which repeats itself 10 times.
There are 3 types of loops which are the for loop, while loop and repeat until loop.

For loop

The for loop uses a loop counter variable, which it adds 1 to each time, to loop from a first number to a last number.
program Loops;

var
   i: Integer;

begin
   for i := 1 to 10 do
      Writeln('Hello');
end.

If you want to have more than 1 command inside a loop then you must put them between a begin and an end.
program Loops;

var
   i: Integer;

begin
   for i := 1 to 10 do
      begin
         Writeln('Hello');
         Writeln('This is loop ',i);
      end;
end.

While loop

The while loop repeats while a condition is true. The condition is tested at the top of the loop and not at any time while the loop is running as the name suggests. A while loop does not need a loop variable but if you want to use one then you must initialize its value before entering the loop.
program Loops;

var
   i: Integer;

begin
   i := 0;
   while i <= 10
      begin
         i := i + 1;
         Writeln('Hello');
      end;
end.

Repeat until loop

The repeat until loop is like the while loop except that it tests the condition at the bottom of the loop. It also doesn't have to have a begin and an end if it has more than one command inside it.
program Loops;

var
   i: Integer;

begin
   i := 0;
   repeat
      i := i + 1;
      Writeln('Hello');
   until i = 10;
end.

If you want to use more than one condition for either the while or repeat loops then you have to put the conditions between brackets.
program Loops;

var
   i: Integer;
   s: String;

begin
   i := 0;
   repeat
      i := i + 1;
      Write('Enter a number: ');
      Readln(s);
   until (i = 10) or (s = 0);
end.

Break and Continue

The Break command will exit a loop at any time. The following program will not print anything because it exits the loop before it gets there.
program Loops;

var
   i: Integer;

begin
   i := 0;
   repeat
      i := i + 1;
      Break;
      Writeln(i);
   until i = 10;
end.

The Continue command will jump back to the top of a loop. This example will also not print anything but unlike the Break example, it will count all the way to 10.
program Loops;

var
   i: Integer;

begin
   i := 0;
   repeat
      i := i + 1;
      Continue;
      Writeln(i);
   until i = 10;
end.