MainPage

PASCAL

Arithmetic
Arrays
Boolean Operators
Case
Comparisons
Declarations
Field Width + Precision
Functions
Identifiers
Loops
Order of Operations
Procedures
Records
Recursion
Searching
Sets
Sorting
Standard Arithmetic Functions
The Maze
Writing Lines



= = = = Identifiers = = = =

==> Not case sensitive
==> Only the first 8 characters matter (ex: "WeightAtStart" is equivalent to "WeightAtEnd")


CANNOT...


Assigning values to a char:
NO => Symbol:= %;
YES => Symbol:= '%';


NOTE:
Identifiers declared in a procedure are local identifiers, and are thus invisible to the outside program.



= = = = Declarations = = = =

program Name;

const
   Pi=3.1415926; (Digits of Pi)
   {Note how we use = and not :=}
   ...

type
   Digit=0..9;
   {Note how we use = and not :=}

var
   Frequency: array [digit] of real;
   blah: real;
   blah, bahh: integer;
   ArrayName: array [..] of variabletype;
   {Note: Subranges must be ordinal}
   SeatSold: array ['A'..'Z',1..30] of boolean;

procedure MEP (A,B,C: integer);
   < declarations >
   begin
   ...
   end;

function MEPNUMBER (First,Second: integer): integer;
{Note: the integer on the end declares the value type returned by the function - declares function type)
   < declarations >
   begin
   ...
   end;



NOTE:
Variable types... integer, real, boolean, char, array, stringtype


NOTE:
Procedure and Function declaration order is insignificant UNLESS a procedure is called within another procedure
==> The called procedure must then be declared first



= = = = Writing Lines = = = =

writeln('I can have ',max,' pieces of pie today. Why wouldn''t I?')



= = = = Field Width + Precision = = = =

Suppose:

X:=123.45;
Y:=-9.876;


STATEMENT OUTPUT
writeln(X:8:2) ,,123.45
writeln(Y:8:1) ,,,,-9.9
writeln(-45.67:12:6) ,,-45.670000



Strings + Field Width:

writeln('Ash Wreungson':15) ==> ,,Ash Wreungson
writeln('Charles Booger':9) ==> Charles B



= = = = Arithmetic = = = =

M div N ==> division with no remainder (requires integer input)
M mod N ==> only the remainder


NOTE:
M mod -N ==> ERROR



= = = = Standard Arithmetic Functions = = = =


Identifier Function Example
SQR squaring ex: sqr(3)=9
SQRT square root ex: sqrt(4)=2
ABS absolute value ex: abs(-4)=4
SIN Note: Input in RADIANS

Note: Pi radians = 180�
COS
TRUNC eliminates post-decimal numbers ex: trunc(7.12)=7    ex: trunc(7.99)=7
ROUND rounds to integer ex: round(7.12)=7    ex: round(7.99)=8
ODD boolean function => true implies odd entry, false implies even entry
PRED predecessor function ex: pred(7)=6
SUCC successor function ex: succ(7)=8


NOTE:
Round can be used to round to a certain precision.. ex: 7.12 => 7.1



= = = = Comparisons = = = =


=
<>
<
<=
>
>=



= = = = Boolean Operators = = = =


"and"   "or"   "not"

TRUTH TABLE

P Q P and Q P or Q not P
T T T T F
T F F T F
F T F T T
F F F F T




= = = = Order of Operations = = = =

not
* / div mod and
+ - or
< <= = <> > >=


NOTE:
Equal precedence => Left to right in statement



= = = = Case = = = =

Let "score" be an integer, and "grade" be a char

case score of
   8,9,10: Grade:='A';
   4,5,6,7: Grade:='B';
   0,1,2,3: Grade:='C';
end
{of case}

NOTE:
The expression following case must be ordinal



= = = = Sets = = = =

Sets are groups of ordinal values enclosed in square brackets and separated by commas

ex: ['A','E','F']
ex: [0,1,4,8,17]



NOTE: All values must be of one type
NOTE: repetitions are ignored
NOTE: order is not significant

Sequential ordinal values can be replaced with two dots
[0,1,2,3,4,5]
is equivalent to [0..5]

An expression in the form < expression > in < set > is a boolean expression with value true if the expression exists in the set
4 in [0..9]
has value true


Useful Application:

If Grade in ['A'..'D','F'] then
   case Grade of ...




= = = = Loops = = = =

FOR LOOP

For i := 1 to 3 do
begin
   blah
end


NOTE:
To count downwards, replace "to" with "downto"


WHILE LOOP

while < expression > do
begin
   blah
end



REPEAT LOOP

repeat
   statement;
   ...
   statement;
until < expression >



EOF (End of File), EOLN (End of Line)

while not eoln do
begin
   read(NextChar);
   write(NextChar);
end




= = = = Arrays = = = =

Set value to Array components before anything is done with them

for i := 1 to 26 do
begin
   LetterFrequency[i]:=0;
end

inc(ArrayName[A]);
==> ArrayName[A]:=ArrayName[A] + 1;


2D ARRAYS

var
   SeatSold: array ['A'..'Z',1..30] of boolean;


Component example: SeatSold[A,3]


WATCH OUT! The following would occur 11 times! (0,1,2,3,4,5,6,7,8,9,10)

count:=0;
while count <= 10 do
   BLAH




= = = = Procedures = = = =

Procedures are terminated with end;


PARAMETERS

ex1{VALUE PARAMETER}:
procedure WriteMin(A: integer; B: integer; C: integer);


ex2{VARIABLE PARAMETER}:
procedure Change(var B: integer);

{Note: the argument in a variable parameter must be a variable}


Both Parameter Types can be used in the same procedure...

ex3{BOTH PARAMETER TYPES}:
procedure ProcessSale(BasePrice,TaxRate: real; var Tax: real; var FinalPrice: real);



CALLING PROCEDURES

To call a procedure during a program, simply write the procedure's identifying name

Calling ex1:
WriteMin(X,Y,Z)
WriteMin(X+3,Y*5,Z)



NOTE:
Parameters require a single word for a variable declaration

EX{ BAD VERSION }:
procedure ArrayThang(Name: array [1..20] of char);



EX{ GOOD VERSION }:
type
   MEP = array [1..20] of char;

procedure ArrayThang(Name: MEP);




= = = = Functions = = = =

Functions are terminated with end;


USING FUNCTIONS

function Smaller(First,Second: integer): integer;
   ...

LittleOne:= Smaller(A,B);

{This would send A and B into Smaller, which would output the answer value}


RANDOM NOTE:
Function page; causes printer to start a new page


BOOLEAN FUNCTIONS

ex:

if (12 < Age) and (Age < 20)
   then
   ...


The fragment above can easily be replaced by the following -

if Teen(Age)
   then
   ...


- given that Teen is a function with defiinition

function Teen(Number: integer): boolean;
begin
   if (Number > 12) and (Number < 20)
     then
       Teen:=true;
     else
       Teen:=false;
end;




= = = = Searching = = = =

SEQUENTIAL SEARCH

const
   Max = ...;

type
   ItemType = ...;
   ListType = array [1..Max] of ItemType;


function SeqSearch (List: ListType; Item: ItemType): integer;

var
   I: integer;
   Found: boolean;

begin
   SeqSearch := 0;
   I := 1;
   Found := false;
   while (I <= Max) and (not Found) do
   begin
      if List[I] = Item
         then
         begin
            SeqSearch := I;
            Found := true;
         end
         else
            I := I + 1
   end;
end;






BINARY SEARCH

NOTE:
Assume elements in the list are in ascending order

const
   Max = ...;

type
   ItemType = ...;
   ListType = array [1..Max] of ItemType;


function BinSearch (List: ListType; Item: ItemType): integer;

var
   Bottom: integer;
   Top: integer;
   Middle: integer;
   Found: boolean;

begin
   Bottom := 1;
   Top := Max;
   Found := false;
   BinSearch := 0;

   while (Bottom <= Top) and (not Found) do
   begin
      Middle := (Bottom + Top) div 2;
      if List[Middle] = Item
         then
         begin
            Found := true;
            BinSearch := Middle
         end
         else
            if List[Middle] < Item
               then
                  Bottom := Middle + 1
               else
                  Top := Middle - 1
   end
end;




= = = = Sorting = = = =

INSERTION SORT

for Top := 2 to Max do
begin
  Temp := List[Top];
  I := Top;
  while List[I-1] > Temp do
  begin
    List[I] := List[I-1];
    dec(I);
  end;
  List[I] := Temp;
end;






SELECTION SORT

Assume the same declarations as provided in "Searching".

procedure SelectSort (var List:ListType);

var
   Top: integer;
   LargeLoc: integer;
   I: integer;
   Temp: ItemType;

begin
   for Top := Max downto 2 do
   begin
      LargeLoc := 1;
      for I := 2 to Top do
      if List[I] > List[LargeLoc]
         then
            LargeLoc := I;
      Temp := List[Top];
      List[Top] := List[LargeLoc];
      List[LargeLoc] := Temp
   end
end;




= = = = Recursion = = = =

Given t(1)=2 and t(N)=3t(N-1)-1, the following recursive function finds the value for any input of N | N > 1

function Term (N: integer): integer;

begin
if N = 1
   then
      Term := 2
   else
      Term := 3*Term(N-1)-1
end;


The function Term calls upon itself for a value of Term(N-1). This process continues until N=1 is called, where Term gives 2.





Towers of Hanoi problem:

Move all of the disks from Needle1 to Needle3 (using Needle2 as necessary) subject to the following conditions: Given Height (number of disks), Start (the starting needle), and Finish (the finishing needle), the following procedure writes the moves required to complete the problem.

procedure MoveTower (Height,Start,Finish: integer);

var
   Intermediate: integer;
{the intermediate needle number}
begin
   if Height = 1
      then
         writeln(Start:1,'------>',Finish:1)
      else
      begin
         Intermediate := 6-(Start+Finish);
         MoveTower(Height-1,Start,Intermediate);
         writeln(Start:1,'------>',Finish:1);
         MoveTower(Height-1,Intermediate,Finish)
      end
end;




= = = = The Maze = = = =

Problem:
Given a starting point in a maze, find an exit point. If the search is successful, print the path.


Solution:

program SolveMaze;

const
  MaxRow = 7;
{number of rows in maze}
  MaxCol = 11;
{number of columns in maze}
  Barrier = 'B';
{barrier}
  OpenPath = '.';
{available path}
  WasHere = '-';
{path that has been tried}
  GoodPath = '+';
{path that leads to exit}
  Exit = 'X';
{exit point}

type
  RowRange = 1..MaxRow;
  ColRange = 1..MaxCol;
  CharArray = array [RowRange,ColRange] of char;

var
  Maze: CharArray;
{array representing the maze}
  Row: RowRange;
{row coordinate}
  Col: ColRange;
{column coordinate}
  Successful: boolean;
{set to true if path found}



procedure MoveFrom (Row: RowRange; Col: ColRange; var Maze: CharArray; var Successful: boolean);
{This procedure attempts to find a path from start to exit. If search successful, WasHere on the correct path is changed to GoodPath, and Successful is set to true.}
begin
  if Maze[Row,Col]=Exit
    then
      Successful := true;
    else
    begin
      Maze[Row,Col] := WasHere;
      if Maze[Row,Col+1] = OpenPath or Maze[Row,Col+1] = Exit
        then
          MoveFrom(Row,Col+1,Maze,Successful);
      if not Successful
        then
          if Maze[Row+1,Col] = OpenPath or Maze[Row+1,Col] = Exit
            then
              MoveFrom(Row+1,Col,Maze,Successful);
      if not Successful
        then
          if Maze[Row,Col-1] = OpenPath or Maze[Row,Col-1] = Exit
            then
              MoveFrom(Row,Col-1,Maze,Successful);
      if not Successful
        then
          if Maze[Row-1,Col] = OpenPath or Maze[Row-1,Col] = Exit
            then
              MoveFrom(Row-1,Col,Maze,Successful);
      if Successful
        then
          Maze[Row,Col] := GoodPath
    end
end;



procedure ReadInitial (var Maze: CharArray; var StartRow: RowRange; var StartCol: ColRange);

{This procedure reads a character array maze of dimensions [1..MaxRow,1..MaxCol] and the coordinates (StartRow,StartCol) of a starting position in Maze.}

var
  Row: RowRange;
  Col: ColRange;

begin
  for Row := 1 to MaxRow do
  begin
    for Col := 1 to MaxCol do
      read(Maze[Row,Col]);
    readln
  end;
  readln(StartRow,StartCol)
end;



procedure Print (Maze: CharArray);

{This procedure prints the character array Maze having bounds [1..MaxRow,1..MaxCol]}

var
  Row: RowRange;
  Col: ColRange;

begin
  for Row := 1 to MaxRow do
  begin
    for Col := 1 to MaxCol do
      write(Maze[Row,Col]);
    writeln
  end
end;



begin
  ReadInitial(Maze,Row,Col);
  Successful := false;
  MoveFrom(Row,Col,Maze,Successful);
  Print(Maze);
  writeln;
  if Successful
    then
      writeln('Successful path is shown by ',GoodPath)
    else
      writeln('No path to exit from given location')
end.




= = = = Records = = = =

type
  Date =
    record
      Year: integer;
      Month: 1..12;
      Day: 1..31
    end;


var
  BirthDate: Date;
  DeathDate: Date;



The use of type definitions is not even required! Simply state the variable type as a record.

var
  NextPerson =
    record
      Name: packed array [1..NameLength] of char;
      MEP:
        record
          ...
        end;
      ...
    end;



Given the declarations at the top of this section, the following statements are all valid:

BirthDate.Year := 1987
readln(BirthDate.Year,BirthDate.Month,BirthDate.Day)
writeln('Life Span:',(DeathDate.Year-BirthDate.Year):1)



NOTE:
To compare the variables BirthDate and PresentDate for equality, it is INVALID to say
if BirthDate = PresentDate

The correct way would be to say
if (BirthDate.Year=PresentDate.Year) and (BirthDate.Month=PresentDate.Month) and (BirthDate.Day=PresentDate.Day)



The with statement.

Given that Candidate is a variable with record values for name, sex, and age, here are two ways of writing the information of Candidate:

writeln(Candidate.name);
writeln(Candidate.age);
writeln(Candidate.sex);

with Candidate do
  begin
    writeln(name);
    writeln(age);
    writeln(sex);
  end;
Hosted by www.Geocities.ws

1