• Keine Ergebnisse gefunden

RESERVED WORDS

Im Dokument Turbo Tutor A Self-Study (Seite 78-86)

When you begin writing programs, you will see that identifiers are used virtually everywhere. You will create your own identifiers for almost every data type, data object, and piece of code that you use.

Aside from the syntax requirements we just covered, there are almost no limitations on the names you can give identifiers. There are, how-ever, a few combinations of letters that cannot be used as identifiers because Pascal uses them as reserved words.

Reserved words (listed in Table 7-1) are words that have special mean-ings when used in your programs. They cannot be used for any other purpose (except in comments-we'll talk more about them later on).

For example, you can't declare a variable named program, or name a program begin. You can use reserved words only in the way Pascal decrees.

To help you remember which are the reserved words as you look at sample programs, they are shown in boldface type throughout this and other Borland manuals. (Note, however, that reserved words do not appear bold when you type them into a program.)

and Standard Pascal Reserved Words

for mod procedure Additional Turbo Pascal Reserved Words absolute between runs. For instance, suppose you want to calculate a percentage based on a fraction, as follows:

100 * Numerator / Denominator

where * represents multiplication and / represents division. In this example, the number 100 is a con,stant (in fact, the number 100 is implicit in the very idea of a percentage). We therefore type it in as an explicit constant in the program.

The Basics of Pascal 59

Constants are not limited to numbers, as shown in the first sample program at the end of Part 1. When we write

Writeln('Hello world, my name is Joe')

the string of characters 'Hello world, my name is Joe' is a constant;

more specifically, it is a string constant. The standard Pascal language allows you to use constants of types integer, real, char, and boolean, plus string constants.

Figure 7-4 sho;'s the syntax diagram for a constant. Beginning in the upper left-hand corner (at the word "constant"), you can choose one of three possible paths: to a box, circle, or oval. If you take the upper path, you may select an optional sign ("

+"

or "-"), then either a constant identifier or an unsigned number (each of which is explained in another syntax diagram). Pursuing the lower path requires a string (a piece of text consisting of zero or more characters surrounded by single quotes). You can take either of these paths, but not both, when making a constant.

constant identifier constant

unsigned number

Figure 7-4 Syntax Diagram of Constant

Constant Definitions

To show how a constant definition might be useful, consider the following problem. Suppose a programmer had to write a program to compute compound interest on a bank account. Since bankers fre-quently use the constant "e" (which has the value 2.718281828) when doing calculations, the programmer would probably have to type this long number several times. The repetitiveness of such a task creates room for error-one that could cost the bank money. To avoid this problem, the programmer could declare e as an identifer to represent the constant:

const

e = 2.718281828;

This would replace the ponderous string of digits with a single charac-ter! After this definition, every mention of the identifier e would be equivalent to typing in the long real number. Constants are defined in a part of your program called a constant definition part. The syntax of this part of a program is shown in Figure 7-5 and Figure 7-6.

constant - - .

definition simple constant definition

part

typed constant definition

Figure 7-5 Syntax Diagram of Constant Definition Part

simple constant definition

-.1

identifier

~

constant

~

Figure 7-6 Syntax Diagram of Simple Constant Definition

Again, to practice your use of syntax diagrams, you may want to trace through the previous diagrams (as well as those in the back of the book) to verify that the deftnition of e really has the correct syntax.

Since this is only a brief introduction, the details of typed constants, and how to defmethem, will be given in future chapters, along with all of the rules for declaring constant identifters.

VARIABLES

In almost any program, you'll need to use pieces of data whose values change during program execution. These data items are called variables.

A variable is a place in your computer's memory where this data is kept.

All variables have names. Like all the other names that you declare when you write a program in Turbo Pascal, the name of a variable is an identifier, and should conform to the syntax for an identifter as shown previously. When you tell Turbo Pascal that you intend to use a variable in your program, you must give the compiler the variable's name and its data type. This is called a variable declaration, and causes Turbo Pascal to set aside a place in memory for the variable and to remember its name.

Variable Declarations

Variable declarations are made in a part of your program called (not surprisingly) the variable declaration part. Here are some examples of variable declarations:

The Basics· of Pascal 61

var

FirstInteger : Integer;

SecondInteger, ThirdInteger Integer;

ASCII_Character : Char;

RealNumber : Real;

The preceding declarations define three variables of type integer, plus one each of types char and real. Note that variables of the same type can be grouped into the same declaration, separated by commas.

(Secondlnteger and Thirdlnteger are declared this way.) The syntax of this part of a program is shown in Figure 7-7.

variable declaration part

Figure 7-7 Syntax Diagram of Variable Declaration Part

As before, this syntax diagram hints at an advanced feature (absolute variables) that we are not ready to explain in detail just yet. For the moment, ignore the branch of the syntax diagram containing this reserved word.

OPERATORS

An operator is a special character, a group of special characters, or a reserved word that Turbo Pascal uses to indicate that an operation (arithmetic, for instance) is to be performed on one or more pieces of data. Some operators, like

+,

will already be familiar to you from arithmetic or algebra. Others, like * (for multiplication), represent familiar operations that have been adapted to the limited character set of a computer keyboard. (Most computers, like typewriters, do not have a multiplication symbol to represent multiplication.) And still others, like div or mod, are unique to the Pascal language.

Here are the operators you can use in Turbo Pascal:

not

* / div mod shl shr and

U nary minus operator Negation operator Multiplication operators Addition operators

+ - or lor

= ( ) (= )= ( )

in

Relational (comparing) operators Set membership operator

The unary minus operator, which is the - sign that immediately precedes a number, does the same thing it does in familiar arithmetic: it changes a value sign. Thus, if the variable A has the value 5, writing -A would yield the value - 5.

The not operator takes a boolean value (TRUE or FALSE) and inverts it. Thus, not TRUE is the same as FALSE, and not FALSE is the same as TRUE.

The * and / operators indicate multiplication and division, respectively.

The div operator represents a special kind of division operation, in which the remainder is thrown away; mod (short for modulo) divides two integers and simply returns the remainder.

The shl and shr operators are special low-level operations that shift the bits of a byte or integer. We'll describe exactly how they work in later

chapters. .

The

+

and - operators are the same operations you've seen in familiar' arithmetic, and produce the sum or difference of two numbers.

The and and or operators work on pairs of boolean values. The value TRUE is produced by and if both of its operands are TRUE; or if either of its operands are TRUE. These two operators can also be used to do bit math on bytes and integers.

The relational operators (=, <, >, < =, > =, <

»

compare numbers and return boolean values based on the results. They should all be familiar except for < >, which is the way the inventor of Pascal chose to represent the not-equal sign (f.) on a computer.

Finally, the in operator determines whether or not an object is in a set.

We'll discuss sets and how to use them shortly.

EXPRESSIONS

You've probably seen expressions before, perhaps in science and math classes where they were called formulas (or, if you want to be classical, formulae). Formulas that calculate such things as the circumference of a circle or the velocity of a falling object with respect to time are just expressions. In fact, FORTRAN (one of the earliest programming languages) stands for FORmula TRANslator.

In Pascal, expressions are combinations of identifiers, constants, and/or operators that describe how to produce a new piece of data from one or more existing ones. When an expression is evaluated, the calculations within it are carried out. The result is a single value.

Like all data used in a Turbo Pascal program, the result of an expres-sion has a data type. This type mayor may not be the same as that of the constants or variables within it. For instance, an expression such as

The Basics of Pascal 63

first_integer + second_integer + third_integer

which adds the contents of three integer-type variables, is said to be an integer expression. However, the expression

first_integer < second_integer

which compares two integers, yields a boolean value (TRUE or FALSE) that indicates whether or not the firsLinteger is less than the seconcLinteger.

The Order of Operations in Expressions

If you've taken a course in algebra, you probably remember the Order of Operations-which means the order in which you perform opera-tions in an expression. In this section, we will demonstrate why this ordering is necessary, and how Pascal handles expressions in which order makes a difference.

Suppose you asked the computer to evaluate the expression 3

+

4 * 2 (remember that * denotes multiplication). How would the computer calculate the result? The following shows two possible ways:

3 4

+4

*

2

7

8

*2 +3

14 11

The example on the left adds 3 to 4, totaling 7, then multiplies the total by 2 to get 14. The example on the right first multiplies 4 by 2 to get 8, then adds 3 to get 11. Which answer is correct? Well, a long time ago, mathematicians ran into this same dilemma, and set up a series of rules to determine how to evaluate expressions in an unambiguous way.

Pascal follows these rules, and added a few more for its own unique operations.

The first rule to remember is that Pascal will always perform multipli-cation and division operations before addition and subtraction opera-tions, unless the addition or subtraction operation is encased in parentheses, thereby causing the multiplication or division operation to follow. By applying this rule, we can see that the expression in the previous example will evaluate to 11, not 14. However, if we were to

add parentheses to the previous expression to make (3

+

4) * 2, the addition would be performed first and then the multiplication.

The second rule you should know is that operations of the same kind (multiplication/division, addition/subtraction) are performed from left to right. Thus, the expression 10 / 5 * 2 would be evaluated as shown:

10 5

/ 5

and not

*

2

"2 10

*

2 /10

4 1

If you wanted the second answer, you would indicate that by writing the expression as 10/ (5 * 2). In this case, the parentheses indicate that the multiplication should occur first.

The third rule is that unary operations (that is, operations that operate on only one object) are performed before any of the others. For instance, in the expression -5

+

10, the unary minus before the number 5 applies ollly to the 5, not to the whole expression 5

+

10.

The result of the expression is therefore 5, not -15!

Parentheses can be used to override the order of operations for unary operators, as well. The expression - (5

+

10) evaluates to -15, as you might expect.

Pascal extends the rules we just described to apply to the relational and set membership operations as well. The relational operations are per-formed after the addition operations, and the set membership opera-tion follows. The complete table of operators given earlier was, in fact, intentionally laid out in order of precedence-that is, with the opera-tions that are done first above those that are done afterward.

Exercises Evaluate each of the following expressions according to the Order of Operations used in Pascal.

1. 4*6/2+3 2. (4 * 6) / 2

+

3 3. 4 * (6/2

+

3) 4. (4 * (6 / 2)

+

3) 5. 4 * ( (6/2)

+

3)

6. (4 * 6) / (2

+

3)

Now, check your answers by inserting them into the following short program and running it. The program is shown as ready to run the first example.

The Basics of Pascal 65

progral calculate;

begin

Writeln(~

*

b / 2 + 3);

end.

STATEMENTS

A statement is a part of a program that tells the computer to perform an action. In the sample program in Chapter 6, the statement

Writeln('Hello, world, my name is Joe')

tells the computer to display a string on the screen. When statements occur in succession, they must be separated from one another by a semicolon (;). Here are some more examples of statements:

Value1 := Value2 + Value3;

Radius .= ~0.25;

if Value! ) 100 then

Writeln('Value1 is greater than 100');

The first statement given is an assignment statement. It is called this because it evaluates the expression Value2

+

Value3, and assigns the result of the addition operation to the variable Valuel (that is, it puts the result in the place in memory reserved for Value1). Valuel retains this result as its variable unless it is specifically changed by the program.

The second statement is also an assignment statement. Here, the constant value 40.25 is assigned to the variable Radius. The last state-ment is called an

if

statement. This kind of statement instructs the computer to perform a certain action only if a particular condition is met; in this case, if Valuel is greater than 100. Note that this statement actually contains another statement (the Writeln statement). This is a common occurrence in Pascal, and we'll say more about it later.

COMMENTS

Last, but not least, there is the Pascal construct that causes the com-puter to do absolutely nothing at all: the comment. A Pascal comment is a string of characters starting with the character" {" and ending with the character "}". The space within the braces can contain any kind of text at all (except, of course, more braces), and everything within the braces will be completely ignored by the compiler. (Chapter 8 details another method of commenting.)

{ This is an example of a comment. Turbo Pascal will ignore this text. }

At this point, you might well ask, "If comments are useless to the compiler, and it completely ignores them anyway, then why are they part of the language at all?" The answer is that comments are very useful to the reader who is trying to understand, change, and/or fix a program. Now, Pascal is designed to make programs more readable than many other languages; however, it is still possible to come back to your own code only a month after writing it, and discover that you no longer understand how it works!

In such situations, comments can save the day because they allow you to attach notes to anything and everything within your program. As you read through the following example, note the liberal use of com-ments to make the program easier to understand.

Im Dokument Turbo Tutor A Self-Study (Seite 78-86)