We have already become familiar with one of the most frequently used operators in the Turbo Pascal language - the assignment operator. The rest of the language operators are discussed below.

Compound operator is a sequence of arbitrary program statements enclosed in operator brackets - reserved words begin... end. Compound operators are an important tool of Turbo Pascal, making it possible to write programs using modern technology structured programming(without jump operators GOTO).

The Turbo Pascal language does not impose any restrictions on the nature of the operators included in a compound operator. There may be other compound operators among them - Turbo Pascal allows arbitrary nesting depth:

Begin……. begin……. begin …… …… end; ……end; ……end;

In fact, the entire operator section, framed by the words begin... end, represents one compound statement. Because the reserved word end is a closing operator bracket, it simultaneously indicates the end of the previous operator, so precede it with the symbol ";" optional, and in all further examples we will not do this.

Presence of a semicolon before end in previous examples meant that between the last operator and the operator bracket end there is an empty statement. An empty statement does not contain any action, it simply adds an extra semicolon to the program. Basically, the empty statement is used to transfer control to the end of a compound statement.

Operators Pascal language

1. Compound and empty statements

Compound operator is a sequence of arbitrary program statements enclosed in operator brackets.

Turbo Pascal allows arbitrary nesting depth:
Begin
...
Begin
...
Begin
...
End;
End;
End;
Availability; before End - an empty statement.

2. Branch operators

IF<условие>THEN<оператор1>

Condition– a BOOLEAN value or a logical operation. If the condition is true, the statement or block of statements following THEN is executed, otherwise the block of statements after ELSE, if any, is executed.

Conditions can be nested, and in this case, any encountered ELSE part matches the closest THEN part above it.

Example:
Var
A, B, C, D: Integer;
begin
A:=1;
B:=2;
C:=3;
D:=4;
If A > B Then
If C< D Then
If C< 0 Then
C:=0
(note that comes before Else)
(empty operator ";" is not used)
Else
A:=B;
end.
but it could be like this:
If A > B Then
If C< D Then
If C< 0 Then
C:=0
Else
Else
Else A:=B

Consider a program that inputs an arbitrary integer from 0 to 15 and outputs it in hexadecimal:

Program Hex;
Var
Ch: Char;
N: Integer;
Begin
Write("N = ");
Readln(N);
If (N >= 0) And (N<= 15) Then
Begin
If N< 10 Then
Ch:= Chr(Ord("0")+N)
Else
Ch:=Chr(Ord("A")+N-10);
End
Else
Writeln("Error");
End.

3. Repetition operators

For<переменная цикла>:=<начальное значение>To(DownTo)<конечное значение>Do<блок операторов>

The variable must be an integer or enumerated type. When the loop is executed, the loop variable changes from the initial to the final value in increments of 1. If to, then the variable increases if downto– decreases.

The loop execution conditions are checked before the statement block is executed. If the condition is not met, the For loop does not execute. The following program calculates the sum of numbers from 1 to the input:

Program Summa;
Var
I, N, S: Integer;
Begin
Write("N = ");
Readln(N);
S:=0;
For I:=1 To N Do
S:=S + I;
Writeln("Sum = ", S)
End.

While<условие>Do<блок операторов>

The statement block will be executed as long as the condition is true. It is necessary that the value of the condition be able to change during execution of the block of operators, otherwise the execution of the loop will never end (in DOS this will lead to the computer freezing). If the advance condition is false, the block of statements will not be executed even once.

Let's find the machine "epsilon" for a variable of type Real:
Program Epsilondetect;
Var
Epsilon: Real;
Begin
Epsilon:=1;
While Epsilon + 1 > 1 Do
Epsilon: = Epsilon/2;
Writeln("Epsilon = ", Epsilon);
End.

Repeat<тело цикла>Until<условие>

The block of statements, regardless of the value of the condition, will be executed at least once. The loop ends if, after the next execution of the block of statements, the condition evaluates to true.

Example: The program requests the input of one character and displays its ASCII code until a blank character is entered:

Program Code;
Const
Cr = 13;
Var
Ch:Char;
Begin
Repeat
Readln(Ch);
Writeln(Ch," = ", Ord(Ch));
Until Ord (Ch) = Cr
End.

Case<ключ выбора>Of<список выбора>Else<оператор>End;

<ключ выбора> - an expression of any enumerated type,
<список выбора> - one or more structures of the form<значение ключа>:<блок операторов>.

Let's create a program that simulates a calculator. The program enters two lines: the first contains two numbers separated by a space or comma, the second is an arithmetic operation symbol.

2 2
*
The end of work is indicated by entering any character other than +, -, /, *.

Program:
Program Calc;
Var
Operation: Char; (Operation Sign)
X, Y, Z: Real;
Stop: Boolean;
Begin
Stop:= False;
repeat
Writeln; (Empty String - Separator)
Write("X, Y = ");
Readln(X,Y);
Write("Operation: ");
Readln(Operation);
Case Operation Of
"+": Z: = X+Y;
"-": Z: = X-Y;
"*": Z: = X*Y;
"/": Z: = X/Y;
Else
Stop:= True;
End;
If Not Stop Then
Writeln("Z = ",Z);
Until Stop;
End.

Any block of list statements can be preceded by more than one selection value, separated by commas.

Goto<метка>

The label must be described in the descriptions section. The label described in the procedure (function) is localized within it, so transfer of control from outside the procedure (function) to the label inside it is impossible.

An empty statement contains no characters and does not perform any action. Used to organize a transition to the end of a block in cases where it is necessary to skip several statements, but not exit the block. To do this, before reserved word end is followed by a mark and a colon, for example:

Chapter 2. Pascal Language Operators Structural Operators

Structural operators are constructions built from other operators according to strict rules. They can be divided into three groups: compound, conditional and repetition. The use of structure operators in your program is often invaluable because they allow the programmer to make his program dependent on some conditions, such as those entered by the user. In addition, by using repeat operators you get the opportunity to process large amounts of data in a relatively short period of time (this, of course, depends on the processor :)

Chapter 2. Pascal Language Operators Compound Operator

This statement is a collection of an arbitrary number of statements, separated from each other by a semicolon, and delimited by the operator brackets begin and end. It is perceived as a single whole and can be located anywhere in the program where a statement can be present.

Chapter 2. Pascal Language Operators Conditional Operators

Conditional operators are designed to select one of the possible actions for execution, depending on some condition (in this case, one of the actions may be absent). There are special operators for programming branching algorithms in Turbo Pascal. One of them is the conditional If statement. This is one of the most popular tools for changing the order of execution of program statements.

It can take one of the following forms:

If<условие>then<оператор1>

else<оператор2>;

If<условие>then<оператор>;

The operator is executed as follows. First, the expression written in the condition is evaluated. As a result of its calculation, a value of a logical (Boolean) type is obtained. If this value is true, then the statement1 specified after the word then is executed. If the result is “false”, then statement 2 is executed. If instead of operator1 or operator2 there is a series of operators, then this series of operators must be enclosed in operator bracketsbegin...end.

Please note that there is no semicolon before the word else.

Example 1. Write a program that asks for the age of a child and then issues a decision about admitting the child to school (age ³7 years).

If v>=7 then writeln(‘Accepting to school’)

Exercise. Modify this program to cap school enrollment at 16 years of age.

Write('Enter the age of the child');

If (v>=7) and (v<=16) then writeln(‘Принимаем в школу’)

else writeln(‘We do not accept school’);

Example 2. Two numbers are given. Replace the smaller of these numbers with the sum of these numbers, and the larger with the product.

Var x, y,s,p: integer;

Write(‘Enter 2 numbers’);

then begin y:=s; x:=p; end

else begin x:=s; y:=p; end;

writeln('x=', x);

writeln(‘y=’, y);

If the If statement provides a choice between two alternatives, then there is a statement that allows you to choose from an arbitrary number of options. This is the Case selection operator. It orchestrates a transition to one of several options depending on the value of an expression called a selector.

General view: Case k of

: <оператор1>;

: <оператор2>;

: <операторN>

else<операторN+1>

Here k is a selector expression that can only have a simple ordinal type (integer, character, logical). , …- constants of the same type as the selector.

The Case operator works as follows. First, the value of the selector expression is calculated, then the implementation of the operator is provided whose selection constant is equal to the current value of the selector. If none of the constants is equal to the selector value, then the statement following the word "else" is executed. If this word is missing, then the operator located outside the Case boundary is activated, i.e. after the word end.

When using the Case operator, the following rules must be followed:

1. The selector expression can only have a simple ordinal type (integer, character, logical).

2. All constants that precede alternative operators must be of the same type as the selector.

3. All constants in alternatives must be unique within the selection statement.

Operator recording forms:

Interval selector:

1..10: writeln(‘a number in the range 1-10’);

11.. 20: writeln(‘a number in the range 11-20’);

elsewriteln('number is out of range')

Integer type selector:

Example 1. Create a program that, based on the entered number of the day of the week, displays its name on the screen.

Write('Enter the day of the week');

1: writeln('Monday');

2: writeln('Tuesday');

3: writeln('Wednesday');

4: writeln('Thursday');

5: writeln(‘Friday’);

6: writeln('Saturday');

7: writeln(‘Sunday’)

elsewriteln(‘There is no such day’);

Example 2. Create a program that, based on the entered month number, displays the name of the season.

Write('Enter month number');

1, 2, 12: writeln(‘Winter’);

3, 4, 5: writeln('Spring');

6, 7, 8: writeln(‘Summer’);

9, 10, 11: writeln(‘Autumn’)

elsewriteln(‘There is no such month’);

5. Language operators in Turbo Pascal 7

Language operators describe certain algorithmic actions that must be performed to solve a problem. The body of the program can be represented as a sequence of such statements. Consecutive program statements are separated by semicolons.

All Pascal language operators can be divided into two groups: simple and structured.

5.1. Simple Operators

Simple operators are those that do not contain other operators. These include:

  • assignment operator;
  • reference to procedure;
  • unconditional jump operator GOTO;
  • empty operator.

The procedure will be discussed in clause 10.1, the rest - in this section.

5.1.1. Assignment operator

This operator assigns the value of an expression to a variable or function. To do this, use the assignment sign:=, to the left of which is the name of the variable or function to which the value is assigned, and to the right is the expression whose value is calculated before the assignment.

It is permissible to assign values ​​to variables and functions of any type, with the exception of the file type. The type of the expression and the type of the variable (or function) must be compatible for assignment (see section 9.3). 1

X:= Y;
Z:=A + B;
Res:= (I>0) and (I I:= Sqr(J) + I * K;

5.1.2. Unconditional GOTO operator. Using labels

The GOTO statement allows you to change the standard sequential order of execution of statements and proceed to program execution starting from a given statement. The operator to which the transition occurs must be marked with a label. The same label must be specified in the GOTO statement. Tags used in Turbo Pascal can be of two types:

  • an integer ranging from 0 to 9999;
  • regular identifier.

All labels used must be listed in a label declaration section beginning with the reserved word label, for example:

label 1, 2, Mark;

Only one operator can be marked with one label. The label is separated from the marked statement by a colon.

The GOTO statement should be used with extreme caution. Its widespread use without any particular reason impairs the understanding of the logic of the program. An unconditional transition can not be carried out from every place in the program and not to every place in the program. Thus, you cannot use this statement to jump from the main program to a subroutine or exit a subroutine; it is not recommended to jump inside a structured statement, since it may give an incorrect result, etc. For more details on such restrictions, see.

Example. Find the quotient of dividing integers.

program EXAMPLE4;
label
Out; (label description)
var
X, Y, Res: Integer;
begin
Write("Enter dividend: "); (display message on screen)
ReadLn(X); (reading the number)
Write("Enter divisor: "); (display message on screen)
ReadLn(Y); (reading the number)
if Y = 0 then
begin (Compound operator, see section 5.2.1)
WriteLn("Division by zero!");
goto Out; (output at zero divisor)
end;
Res:=X div Y;
WriteLn("Quotient equals: ",Res);
Out: (label of "empty" operator)
end.

5.1.3. Empty operator

An empty statement does not perform any action and is not displayed in any way in the program (except perhaps by a label or semicolons separating the empty statement from previous or subsequent statements). It may be required to carry out an unconditional transition to it (see example in paragraph 5.1.2).

Using this operator, variables in Turbo Pascal can receive their values ​​programmatically (that is, not from the keyboard). Format:

<идентификатор (имя) переменной>:= <выражение>

The system first calculates the value of the expression, then assigns it to a variable.

    Compound operator.

A compound operator is a sequence of any Turbo Pascal operators enclosed in operator brackets begin and end. For example:

begin a:=5; write('a=',a); end;

Among the operators of a compound operator there may be other compound operators, that is, any depth of their nesting is allowed. For example:

    Conditional jump operators.

They exist to organize branches depending on the truth or falsity of some condition. There are two such operators: a complete conditional operator and an incomplete conditional operator.

    Full conditional statement

Implements the “full fork” algorithmic design:

Its format:

if <logical expression> then <оператор 1> else <оператор 2>

If, then, else – service words “if”, “then”, “else”. There is no semicolon before the word else. Statement 1 and statement 2 can be either simple or compound statements. A compound statement must be enclosed in parentheses begin and end.

Actions conditional operator: if the logical expression evaluates to true, then operator 1 is executed, if the logical expression evaluates to false, then operator 2 is executed.

    Incomplete conditional statement

Implements the algorithmic design “incomplete fork”

Its format:

if<логическое выражение> then<оператор >

If, then – service words “if”, “then”. An operator can be either a simple operator or a compound operator.

Actions of the conditional operator: if the logical expression evaluates to true, then the statement is executed, if the logical expression evaluates to false, then the conditional statement is skipped and the statement following it is executed.

Conditional operators (complete and incomplete) can have a nested structure, that is, after the words THEN or ELSE, a conditional operator is used again. Service word ELSE always refers to the word closest to the left of THEN.

A conditional statement can contain one simple statement. If the meaning of the task requires inserting several operators, then they are combined into a compound one.

Comment: after the word THEN a new conditional statement cannot be written immediately, but after ELSE it can. For example:

In cases where multiple conditions need to be tested, complex conditional statements are used. They use the logical operators and, not, or. For example:

if ((x>3) and (y>3) and (z>3)) then ...

    Loop organization operators.

A cycle is a section of a program that is repeated many times. To organize a loop in Pascal, three operators are used: an operator with a precondition, an operator with a postcondition, and an operator with a parameter.

    Loop operator with precondition

This statement implements a loop block diagram with a precondition:

Its format:

While <логическое выражение> Do <тело цикла>

While (“for now”), Do (“to do”) are function words.

Operator actions: while the logical expression is true, the body of the loop is executed; Once a Boolean expression evaluates to false, the statement ends and the statement following it is executed. The value of the logical expression is checked before the body of the loop. If the logical expression is false from the very beginning, then the body of the loop is immediately omitted.

If the body of a loop contains a sequence of statements, then it is said to form a compound statement, at the beginning and end of which the operator brackets Begin and End must be written.

If the body of the loop is one statement (not a compound one), then operator brackets are not required. Then the translator considers that the body of the loop ends at the nearest “;”. There are no special words in Pascal to indicate the beginning of a loop and the end of a loop. There are universal words Begin and End for all cases.

    Loop operator with postcondition

This statement implements a loop block diagram with a postcondition:

Its format:

Repeat <тело цикла> Until <логическое выражение>

Repeat (“repeat”), Until (“until”) are function words.

The body of the loop can be either a single or a compound statement, but the use of Begin and End is not required, since the words Repeat and Until themselves act as operator brackets.

Operator actions: the body of the loop is executed, then the value of the logical expression is checked. If the logical expression evaluates to false, then the body of the loop is executed again. This continues until the Boolean expression evaluates to true. That is, the body of the loop repeats its execution if the condition is false. The repetition ends when the condition becomes true. The action of the statement ends and the statement following it is executed. The value of the Boolean expression is checked after the loop body.

Notes:

    Before each execution of the loop body, the Boolean expression must have a specific value.

    The body of the loop must have at least one statement that affects the value of the logical expression, otherwise the loop will run endlessly.

    Eventually the boolean expression must evaluate to a value that ends the loop.

    Loop operator with parameter

This statement implements the block diagram of a loop with a counter. Its format:

for <параметр цикла>:= <арифметическое выражение 1> to <арифметическое выражение 2> do <тело цикла>

for < параметр цикла >:= < арифметическое выражение 1> downto < арифметическое выражение 2> do <тело цикла>

A loop parameter is a variable of any type other than real.

Arithmetic expressions 1 and 2 must be of the same type as the loop parameter. The body of the loop is any Pascal operator (simple, complex, compound).

Operator actions: the loop parameter is assigned the value of the arithmetic expression 1. If it is less (for for- to- do) or more (for for- downto- do) the value of the arithmetic expression 2, then the body of the loop is executed. The loop parameter is then increased (decreased) by the amount specified in the loop body. Then it is again compared with arithmetic expression 2. And so on until the loop parameter becomes greater (less) than the value of arithmetic expression 2. Then the loop operator finishes its work and the next operator is executed.

If the loop parameter is of type integer, then with the word to the step of changing the parameter is equal to one (with downto the step is -1).

This operator has limited use, that is, it can only be used in cases where the number of repetitions of the loop body is known