Pascal was originally designed to teach structured programming techniques. However, Pascal soon proved popular and powerful enough that people started using it to create commercial applications. Unlike C/C++, which emphasizes machine efficiency, Pascal emphasizes readability. Pascal programs may not be as fast or as easy to type as C/C++ programs, but Pascal programs are much easier to read and modify. Because the bulk of programming involves updating an existing program, Pascal is ideally suited for maximizing the efficiency of programmers by making programs easier to understand and update.
Like many programming languages, Pascal has evolved into many different dialects, but one of the most popular Pascal dialects is based on Borland Software's old Turbo Pascal language — Borland Pascal. At one time, the Borland Pascal dialect dominated programming the MS-DOS operating system. However with the introduction of Microsoft Windows, programmers shifted to the easier Visual Basic or the more powerful C/C++. As a result, Pascal has fallen out of favor in North America but maintains a surprisingly large following in Europe and South America.
To create Windows programs with Pascal, Borland Software (www.codegear.com
) introduced Delphi, which was similar to Visual Basic except that it uses an object-oriented version of Pascal — Object Pascal — although it's more commonly referred to as the Delphi programming language. (You can get a free copy of Delphi by visiting www.turboexplorer.com
.)
Because the financial health of Borland Software has gone up and down, a group of programmers have banded together to create the Free Pascal compiler (www.freepascal.org
), which allows you to write Pascal programs for Windows, Linux, and Mac OS X. Best of all, Free Pascal closely follows the Borland Pascal language dialect, which makes it possible to take your old Turbo Pascal programs for MS-DOS (or your newer Delphi programs for Windows) and run them on Mac OS X and Linux with minor modifications.
Although it's unlikely that Pascal will ever regain its popularity as a major programming language, Pascal has inspired other programming languages, most notably the Ada programming language, which is used in critical, real-time systems, such as the Boeing 777 avionics system. As a result, Pascal remains an influential programming language to this day.
The strength (or weakness, depending on your point of view) of Pascal is that it forces you to structure your programs. At the beginning of a Pascal program, you must declare any constants, types, or variables, such as
Program name; Const (* Constants here *) Type (* Type definitions here *) Var (* Variable declarations here *) Begin (* Commands here *); End.
A typical Pascal program might look like this:
Program TaxRefund; Const TaxRate = 0.35; Type ClassLevel = (Upper, Middle, Lower); Var MyClass : ClassLevel; TaxesOwed, Income : integer; Begin Income := 60000; TaxesOwed := Income * TaxRate; If MyClass = Upper then Begin Writeln ('Bribe a corrupt politician.'), End; End.
Pascal ends every statement with a semicolon but uses a period at the end of the entire program.
Pascal/Delphi allows you to enclose comments with curly brackets {}
or a parentheses and an asterisk pair (* *)
, such as
Program name; (* This is a short Pascal program. *) Begin {The Writeln command is used to display text on the screen, much like the Print command in other languages.} Writeln ('This is a simple Pascal program.'), End.
In every Pascal/Delphi program, define a separate section for declaring your variables by using the Var
keyword, such as
Program namehere; Var Variablename1 : datatype; Variablename2 : datatype; Begin (* Commands go here *) End.
Unlike C/C++, Pascal isn't a case-sensitive language, so the variable names TaxRate, taxrate
, and Taxrate
are all considered the same variable.
Strings represent text, such as a single character ('A'
) or several words ('"This is a string of text'"
). To declare a string variable, use the String keyword, such as
Var Variablename1 : String;
In Pascal, strings are enclosed in single quote marks (not double quote marks as in other languages). After you declare a variable to hold a string, you can assign a string to that variable, such as
Variablename1 := 'This string gets stored in the variable.';
If you only want to store a single character, you can use the Char
keyword, such as
Var Variablename1 : Char;
To assign values to a variable in Pascal, use the colon and the equal sign symbols, such as :=
, instead of just the equal sign (=
) like other programming languages.
Whole numbers represent integers such as 349, −152, or 41. A whole number can be positive or negative. The most common type of integer data type is Integer
and is used as follows:
Var Variablename1 : Integer;
To accept different ranges of integer values, Pascal offers several integer data types. For example, if a variable needs only to hold a positive value, you can declare it as a Byte
data type, such as
Var Variablename1 : Byte;
Besides limiting the range of integer values, different integer data types also require different amounts of memory to store that data. The greater the range of values you need to store, the more memory needed (measured in bytes). The smaller the range of values, the less memory required. Table 4-1 shows different integer data types, the memory needed, and the range of values they can hold.
Decimal values are numbers such as 1.88 or −91.4. Just as you can limit the range of integer values a variable can hold, so can you limit the range of decimal values a variable can hold. In Visual Basic, the four types of decimal data types are Single, Double, Currency
, and Extended
, as shown in Table 4-2.
Table VI.4-2. Pascal Decimal Data Types
Data Type | Number of Bytes | Range |
---|---|---|
Single | 4 | 1.5 E-45 to 3.4 E38 |
Double | 8 | 5.0 E-324 to 1.7 E308 |
Currency | 8 | -922,337,203,685,477.5808 to 922,337,203,685,477.5807 |
Extended | 10 | 3.4 E-4932 to 1.1 E4932 |
To declare a variable as a decimal data type, use the Single, Double, Currency
, or Extended
keyword, such as
Var Variablename1 : Single;
Constants always represent a fixed value. In Pascal, you can declare a constant and its specific value as follows:
Const Constantname1 = value;
So if you wanted to assign 3.14
to a pi
constant, you could do this:
Const pi = 3.14;
The three types of operators used are mathematical, relational, and logical. Mathematical operators calculate numeric results such as adding, multiplying, or dividing numbers. Table 4-3 lists the mathematical operators used in Pascal.
Table VI.4-3. Mathematical Operators
Mathematical Operator | Purpose | Example |
---|---|---|
+ | Addition | 5 + 3.4 |
- | Subtraction | 203.9 - 9.12 |
* | Multiplication | 39 * 146.7 |
/ | Division | 45/ 8.41 |
Div | Integer division | 35 div 9 = 3 |
Mod | Modula division (Returns the remainder) | 35 mod 9 = 8 |
Relational operators compare two values and return a True
or False
value. The six relational operators available in Pascal are shown in Table 4-4.
Table VI.4-4. Relational Operators
Relational Operator | Purpose |
---|---|
= | Equal |
<> | Not equal |
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
Logical operators, as shown in Table 4-5, compare two Boolean values (True
or False
) and return a single True
or False
value.
Table VI.4-5. Logical Operators
Logical Operator | Truth Table |
---|---|
And | True And True = True True And False = False False And True = False False And False = False |
Or | True Or True = True True Or False = True False Or True = True False Or False = False |
Xor | True Xor True = False True Xor False = True False Xor True = True False Xor False = False |
Not | Not True = False Not False = True |
The simplest branching statement is an IF-THEN
statement that only runs one or more commands if a Boolean condition is True
, such as
IF condition THEN BEGIN Commands; END;
To make the computer choose between two mutually exclusive sets of commands, you can use an IF-THEN-ELSE
statement, such as
IF condition THEN BEGIN Commands; END ELSE BEGIN Commands; END; END;
If a Boolean condition is True
, the IF-THEN-ELSE
statement runs the first group of commands; but if the Boolean condition is False
, the IF-THEN-ELSE
statement runs the second group of commands. An IF-THEN-ELSE
statement will always run one set of commands or the other.
One problem with the IF-THEN
statement is that it only gives you two possible choices. To offer multiple choices, Pascal also uses the CASE
statement, such as
CASE variable OF value1: BEGIN Commands; END; value2: BEGIN Commands; END; END;
The preceding CASE
statement is equivalent to the following IF-THEN-ELSE
statement:
IF variable = value1 THEN BEGIN Command END; ELSE IF variable = value2 THEN BEGIN Commands; END; END;
To check if a variable matches multiple values, you can separate multiple values with commas or you can match a range of values, such as
CASE variable OF value1: BEGIN Commands; END; Value2..value4: BEGIN Commands; END; END;
The preceding CASE
statement is equivalent to the following IF-THEN-ELSEIF
statement:
IF variable = value1 THEN BEGIN Commands; END ELSE IF (variable >= value2) AND (variable <= value4) THEN BEGIN Commands; END;
A looping statement repeats one or more commands for a fixed number of times or until a certain Boolean condition becomes True
. To create a loop that repeats for a fixed number of times, use the FOR
loop, which looks like this:
FOR variable := Start TO End DO BEGIN Commands; END;
If you wanted the FOR
loop to run five times, you'd set the Start value to 1
and the End value to 5
, such as
FOR variable := 1 TO 5 DO BEGIN Commands; END;
Normally the FOR
loop counts up, but you can use the DOWNTO
keyword to make the FOR
loop count backwards, as shown in this example:
FOR variable = 30 DOWNTO 1 DO BEGIN Commands; END;
If you don't know how many times you need to repeat commands, use a WHILE
or a REPEAT
loop.
The WHILE
loop repeats until a certain condition becomes False
and looks like this:
WHILE condition DO BEGIN Commands; END;
The WHILE
loop checks if a condition is True
. If not, this loop won't even run at least once. If you want a loop that runs at least once, use the REPEAT-UNTIL
loop, which looks like this:
REPEAT Commands; UNTIL condition;
This loop runs at least once before checking a condition. If the condition is True
, the loop stops.
The REPEAT-UNTIL
loop doesn't need enclosing BEGIN-END
keywords because the REPEAT
and UNTIL
keywords serve that function.
You can create a subprogram (or a procedure) by using the PROCEDURE
keyword as follows:
PROCEDURE Name (Parameter list) Const (* Constants here *) Type (* Type definitions here *) Var (* Variable declarations here *) Begin (* Commands here *); End;
Every subprogram must have a unique name, which usually describes the purpose of that subprogram (such as Calculate_Credit_Rating
or DenyHealthBenefits
). The parameter list declares variables to hold any data the procedure may need from another part of the program. For example, a simple parameter list might look like this:
PROCEDURE Name (FirstName : string, Age : integer) Begin (* Commands here *); End;
In the preceding example, a copy of the parameter is passed to the procedure. If the procedure changes the value of that data, the new value of that data appears only in the procedure and not in any other part of the program.
If you want a procedure to change the value of a parameter, declare that variable in the parameter list with the Var
keyword, such as
PROCEDURE Name (FirstName : string, Var Age : integer); Begin (* Commands here *); End;
A function is a special version of a subprogram that always returns a single value. To create a function, use the FUNCTION
keyword, such as
FUNCTION FunctionName (Parameter list) : Datatype; Const (* Constants here *) Type (* Type definitions here *) Var (* Variable declarations here *) Begin (* Commands here *); FunctionName := value; End;
The two main differences between a function and a procedure are that a function needs to define the function name as a specific data type and the last line in the function must store a value into the function name.
Pascal provides three data structures:
Records (known as structures in C/C++) - Stores multiple variables inside a single variable.
Arrays - Stores a list of items that consist of the same data type.
Sets - Stores an arbitrary list of items.
A record is a variable that typically holds two or more variables. To create a record, declare the record under the Type
section and use the RECORD
keyword as follows:
Type Recordname = RECORD Variables : datatype; END;
The name of a record can be any descriptive name, such as Customers
or Students_1stGrade
. Inside a record, you must declare one or more variables like this:
Type Suckers = RECORD Name : string; Address : string; Age : integer; END;
To create an array in Pascal, you must create a variable that represents an array under the Var
section of a program like this:
Var Arrayname : ARRAY [LOWER..UPPER] OF datatype;
If you wanted to create an array to hold five strings, you could do this:
Var HitList : ARRAY [1..5] OF string;
If you don't want your array elements to be numbered from 1 to 5, you could pick any range of numbers, such as
Var HitList : ARRAY [25..29] OF string;
Defining different lower and upper ranges for the size of your array gives you the flexibility of using meaningful array index numbers (such as employee IDs), but at the risk of making the actual size of the array harder to understand. An array bounded by 1..5
easily identifies five elements in the array, but an identical array bounded by 25..29
also identifies five elements in an array but it's not as obvious.
You can also create a dynamic array that can change in size while your program runs. To create a dynamic array, define the array without specifying its size, such as
Var Arrayname : ARRAY OF datatype;
Before you can store data in a dynamic array, define its size with the SetLength
command, such as
SetLength (Arrayname, Size);
So if you created a HitList
dynamic array, you could define its size to hold ten items by using the following:
SetLength (HitList, 10);
When you define the size of a dynamic array, you define only the size of the array because the first element of the array is always 0
. When you want to clear a dynamic array from memory, set the dynamic array's name to NIL
, such as
HitList := NIL;
Pascal includes a unique data structure known as a set. A set lets you define a group of items, such as characters or a range of numbers:
Type Name1 = SET OF (Red, Green, Blue); Name2 = SET OF 1..10;
After you define a set, you can use the In
operator to determine if a variable contains data that's within a set, such as
Program TestMe; Var FixedSet = SET OF 1..10; X : integer; Begin X := 5; If X in FixedSet then Writeln ('The number in X is in the FixedSet range'), End.
In the preceding example, the program checks if the number stored in the X
variable lies within the set of numbers defined by the FixedSet
variable. Because the FixedSet
variable contains 1
through 10, 5
does fall in the set, so the condition X in FixedSet
is True
.
Without sets, a program might resort to multiple IF-THEN
or CASE
statements to determine if a variable falls within a range of values. However, checking if a variable falls within a range of values is a simple one-line command in Pascal. This makes sets one of the more interesting data structures in Pascal, and they aren't commonly found in other programming languages.
The object-oriented version of Pascal is often called Object Pascal or the Delphi language because Delphi uses object-oriented programming. To create an object, you must define a class under the Type
section of a program like this:
Type Classname = CLASS PRIVATE Variablename : datatype; PROCEDURE name (paramater list); FUNCTION name (parameter list) : datatype; PUBLIC Variablename : datatype; PROCEDURE name (paramater list); FUNCTION name (parameter list) : datatype; END;
Any procedure or function declarations defined in a class must be fully defined outside the class.
Anything defined under the PRIVATE
section represents methods and properties that only the object can use. Anything defined under the PUBLIC
section represents methods and properties that other parts of the program can access within that object.
After you define a class, you can create an object from that class by declaring a variable as a new class type, such as
Var Objectname : Classname;
Object Pascal allows only single inheritance — a new class can inherit features from a single class. To create a new class from an existing class, use the CLASS
keyword and include the name of the class to inherit from, such as
Type Classname = CLASS (classToInheritFrom) PRIVATE Variablename : datatype; PROCEDURE name (paramater list); FUNCTION name (parameter list) : datatype; PUBLIC Variablename : datatype; PROCEDURE name (paramater list); FUNCTION name (parameter list) : datatype; END;