A compound statement is several statements combined into one to perform actions in another statement (conditional, loop, selection, etc.)

if x>0 then y:=x+2 else y:=x-2

13. Conditional operator.

b) Branching structure

Conditional jump operator

The conditional jump operator in Turbo Pascal has the form:

if condition then operator 1 else operator 2;

condition is a logical expression, depending on which one of two alternative branches of the algorithm is selected. If the condition value is TRUE, then the operator 1, written after the then keyword. Otherwise it will be executed operator 2, following the word else, while operator 1 skipped. After executing the specified statements, the program proceeds to executing the command immediately after the if statement.

It must be remembered that before keyword else semicolon is never used!

else - part in the if statement may be missing:

if condition then operator 1;

Then in case of failure logical condition control is immediately transferred to the operator that appears in the program after the if construct.

It should be remembered that the language syntax allows only one statement to be written after the then and else keywords, so a group of instructions must be combined into a compound statement (surrounded by operator brackets begin ... end). Otherwise, most often a logical program error occurs when the language compiler does not produce errors, but the program nevertheless works incorrectly.

Examples.

if x > 0 then modul:= x else modul:= -x;

if k > 0 then WriteLn("k is a positive number");

if min > max then begin

14.Transition operator. Labels and jump operators

It can be theoretically shown that the operators considered are quite sufficient for writing programs of any complexity. In this regard, the presence of jump operators in the language seems unnecessary. Moreover, modern structured programming technology is based on the principle of “program without GOTO”: it is believed that the abuse of jump operators makes the program difficult to understand, confusing and difficult to debug.

However, in some cases, using jump operators can simplify a program.

The transition operator has the form:

GOTO<метка>.

Here GOTO - reserved word(go [to label]);<метка>- label.

A label in Turbo Pascal is an arbitrary identifier that allows you to name a certain program statement and thus refer to it. For compatibility with the standard Pascal language, Turbo Pascal also allows the use of unsigned integers as labels.

The label is located immediately before the marked statement and is separated from it by a colon. An operator can be marked with several labels, which in this case are separated from each other by a colon. Before appearing in the program, the label must be described. A label description consists of the reserved word LABEL followed by a list of labels:

Example

1: WriteLn("Go to label 1");

The effect of a GOTO statement is to transfer control to the corresponding labeled statement. When using labels, the following rules must be followed: the label referred to by the GOTO statement must be described in the description section and it must appear somewhere in the body of the program; labels described in the procedure (functions) are localized within it, so transferring control from outside the procedure (function) to a label inside it is impossible. An empty statement does not contain any actions, an extra semicolon is simply added to the program. Mostly empty operator used to transfer control to the end of a compound statement.

Most programmers consider the use of an unconditional jump operator in a program to be a bad form and rarely use it. But, despite this, you need to know it, since it may turn out that you cannot come up with an alternative solution to the problem. Name of this operator Goto, the semantic meaning in the program is “go to...”, and its general appearance is as follows:

Goto m;

m– a label pre-specified in the label description section. The following program shows how the unconditional jump operator works.

1
2
3
4
5
6
7
8
9
10

program goto_primer; (program name)
uses crt; (module connection)
label m; (description of mark m)
begin
write ('Karl Marx' ) ; (string output)
goto m; (requirement to go to tags)
write('clever'); (this statement is skipped)
m: write ('fool' ) ; (navigate to this area)
readkey; (to stop the program)
end.

There are no conditions in this program, but they will be discussed further.

Conditional operator:

In Pascal, to test some part of a program to determine the further path it should take, there is an operator If. Depending on the fulfillment of the logical condition, it indicates which block will be executed next. There are two forms of recording: full and short. The second differs from the first in that it has a branch Else(otherwise).

General view of the short form:

If<условие A>Then<оператор 1>;

General view of the full form:

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

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

In short, statement 1 is executed when condition A is true, otherwise control moves to the next statement. In full form, if condition A is true, then statement 1 is executed, otherwise statement 2 is executed. Remember that there is no semicolon before else.

An example of a program with a conditional statement written in short form:

An example of a program with a conditional statement written in full form:

In Pascal, you can nest one conditional statement within another, and you can do this many times. It should be noted that each Then matches the closest Else.

Selection operator:

When the number of alternatives is more than two, the selection operator is used Case. Its appearance:

Case<селектор>Of

<значение селектора>: <оператор 1>;

<значение селектора>: <оператор 2>;

<значение селектора>: <оператор N>;

Else<оператор>

If the operator selector If was a logical expression, then in Case it is a variable, which can be an integer, enumerable, interval or character type. If the selector matches the value, the corresponding statement is executed. There are three ways to set a selector value:

1) transfer: 1, 10, 100, 1000

2) range: ‘d’..’k’

3) listing and range: 1..10, 20, 30, 50, 70..100

Only one branch (the one that comes first) can be executed in a select statement, even when the selector matches multiple values. Also, unlike If V Case you can put a semicolon before Else.

Consider a program in which the conditions are checked by a selection operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

program case_primer;
uses crt;
var money: char ;
begin
write( ‘First letter of the currency code: ‘) ;
readln(money); (entering a value into a variable)
case money of
'A' , 'a' : writeln ( ‘French franc’) ;
'B' , 'b' : writeln ( 'Dinar' ) ;
'C' , 'c' : writeln ( 'Yuan' ) ;
'E' , 'e' : writeln ( ‘Spanish peseta’) ;
'G' , 'g' : writeln ( ‘English pound sterling’) ;
'I' , 'i' : writeln ( ‘Italian lira’) ;
'J' , 'j' : writeln ( 'Yen' ) ;
'R', 'r': writeln('Ruble');
'U' , 'u' : writeln ( 'US Dollar' ) ;
'X' , 'x' : writeln ( ‘East Caribbean dollar’) ;
else writeln( ‘Unknown unit’)
end ;
readkey;
end.

The program checks the selector to see if it matches the available values. If no matches are found, the block is executed Else.

Transition operator

This time I will continue to consider the topic “Operators”.

(Unconditional) jump statements are designed to transfer control to a statement marked with a label (preceded by the label).

The author's version of the language assumes that the label is formatted as an integer decimal number in the range 1..9999 . Turbo Pascal allows the use of identifiers as labels. When using jump operators, the following rules must be observed:

1) All marks in the block must be described. In this case, each label can be described no more than once. Those. There cannot be two labels with the same name within a block.

2) The label specified in the jump operator must point to (tag) a statement located in the same block as the jump operator itself. Those. Transitions outside or inside procedures (functions) are not allowed.

3) An attempt to jump (transfer control) inside a structure operator can cause unpredictable effects, although in this case the compiler may not produce an error message.

The use of an unconditional jump in a program is considered theoretically redundant, since it can cause confusion in the chain of logically placed program operations, which can lead to great difficulties in debugging and modifying such a program. It is recommended to use transition operators following the following rules:

1) if it seems impossible to do without transition operators, you should strive to use them to transfer control only down the program text (forward); if there is a need to transfer control “back”, it is better to use loop operators (see below);

2) for clarity, the distance between the label and the operator to jump to it should not exceed one page of text (or the height of the display screen), otherwise the meaning of such an unconditional transition will be difficult to grasp.

Labels are defined by descriptions that begin with function word label and contain a sequence of label names separated by commas. To transfer control to the operator marked with a label, an unconditional transition operator is provided goto. A label is separated from the following statement by a ‘:’ (colon). Example:

var j:integer;

(we announce two labels)

label Start, Finish;

Start: writeln(‘Start of program’);

goto Finish;

Finish: writeln('End of program');

Compound operator

The simplest structure operator is the compound operator. This statement specifies the sequence of execution of the operators contained in it. A compound operator is formatted as a list of operators separated from each other by the symbol ‘;’ (semicolon) and enclosed between auxiliary words begin And end.

The need for a compound operator may arise in cases where the syntax Pascal language allows the use of only one operator in a place in the program where a whole series of actions (operators, see examples below) is required. Here's a simple example of a compound operator:

Conditional operator

The meaning of a conditional operator is to analyze a certain logical condition, and in accordance with whether this condition is satisfied or not, transfer control to the corresponding operator. The condition can be an expression that returns boolean value Boolean type. The result of condition analysis can be the value true, i.e. the condition is satisfied and false, i.e. the condition is not met.

The conditional statement is executed as follows. The expression specified after the service word is pre-calculated IF. If the condition is met, then control is transferred to the operator specified after the service word then, if not, then the operator specified after the else service word is executed. In this case, part of the conditional operator, starting with the word else, may be missing. Here are examples of conditional statements:

If Keypressed then writeln('Key pressed');

If A>B then Min:= B

else Min:= A;

if X1 > X2 then begin

The last example is exactly the case when it is necessary for a number of operators to be executed according to the condition, but due to the fact that behind the service word then or else only one statement can follow, that is, it is possible to resolve the situation by using a compound statement containing just a number of those necessary statements.

When composing nested conditional statements, keep in mind that the else branch always belongs to the previous branch IF, which does not yet have an else branch. Those. the following construction

if Condition1 then if Condition2 then Operator1 else Operator2;

for clarity, it can be interpreted as follows

if Condition1 then begin

if Condition2 then Operator1 else Operator2;

It is necessary to be careful when using nested conditional statements, so that in the heat of the moment of composing the next conditional statement of the program, you do not lose sight of what, at first glance, small detail, which can lead to completely different execution of conditional branching.

Variant operator

Quite often a situation arises when a chain of conditional statements grows to enormous proportions, for example, the following example illustrates a branching that is modest in size, but already contains the complexity of perceiving the meaning inherent in it:

type TWay = (Up, Right, Down, Left);

var Way: TWay;

MapX, MapY: word;

if Way = Up then MapY:= MapY - 1

else if Way = Right then MapX:= MapX + 1

elseif Way = Down then MapY:= MapY + 1

else MapX:= MapX - 1;

The last else branch does not have a statement If, since if all three conditions are not met, it would be logical for the operator corresponding to the fourth and last option of possible values ​​of the type to come into effect TWay.

In this case, we are lucky that the type TWay has only four possible values. Would composing such branches become a chore if there were ten or more options? But in the presented branching a simple pattern is visible. So is it possible to somehow simplify it and make it more efficient and readable? It is possible, and for this purpose the language provides a variant operator, the construction of which can contain an arbitrary number of alternatives for a certain expression. Then the last example can be rewritten in a new way:

case Way of

Up: MapY:= MapY - 1;

Right: MapX:= MapX + 1;

Down: MapY:= MapY + 1;

Left: MapX:= MapX - 1;

Well, that's a completely different matter. Now let's look at the execution order of this statement. The value of the expression following the function word is pre-calculated case, but since in this case the variable name is Way, then the value of this variable is read. The resulting value is compared in turn with each alternative (constant, immediate value) specified after the service word of. If the value of an expression is equal to the next constant, the alternative operator following this constant, separated from it by a colon, is executed. After the alternative statement completes execution, action moves to the statement following the variant statement. If the value does not match Way with no constant this operator option does not perform any action.

But what if it is necessary to provide a certain branch of operators that would be executed if the value of the expression does not match any constant? You can use an else alternative for this, for example:

case Way of

Up: MapY:= MapY - 1;

Right: MapX:= MapX + 1;

Down: MapY:= MapY + 1;

else MapX:= MapX - 1;

Therefore, the construction built using the case operator is completely equivalent to the construction built earlier using the operator IF. In addition, it is clearer and there is no risk of getting confused in numerous else.

Once again, I want to draw your attention to the fact that the constants in the variant operator can be both direct integers and the names of untyped constants described earlier. The use of typed constants in alternatives to the variant operator is not allowed. Moreover, in each option you can specify a whole list of constants separated by commas or a range of values, for example:

case Way of

Up, Down: writeln(‘Moving vertically’);

Right, Left: writeln(‘Moving horizontally’);

case X of

10,20,30: writeln('tens');

1..9: writeln('units');

In the last construction the operator writeln('units') will be executed if the variable X has one of the values 1,2,3,..,8,9 .

As you may have noticed, I aligned the lines with constants by colons, since it seems to me that this type is more visual, although this is a matter of taste, and as you know, there is no friend for taste;O)

The variant operator should be used in accordance with the following rules:

1) Acceptable values ​​of the expression - “switch”, written after the function word case, must satisfy the discrete type: for an integer type they must lie in the range -32768..32767 .

2) All specified alternative constants must be of a type compatible with the type of the expression.

3) Constants in alternatives must not be repeated within a variant statement, and ranges must not overlap and must not contain constants specified in this or other alternatives.

One more thing. Design case provides one statement for each alternative. If you need to execute multiple statements, you should group them into a compound statement begin..end. It is possible to specify an empty operator for an alternative by placing the ";" symbol. (semicolon) immediately after the colon, which will do nothing. And the branch syntax else provides for specifying a sequence of operators separated by the symbol ‘;’ (semicolon).

When solving most problems, computational processes branch out. Selective statements are used to determine the further direction of program execution. This class includes the conditional operator and the selection operator.

The conditional operator, used to branch the algorithm into two directions, is one of the key tools not only in Pascal, but also in any other programming language.

The conditional statement can be in two forms: full and short.

Full form of the conditional statement

The full form of the conditional operator in Pascal is as follows:

  • if expression then
  • operator1
  • operator2

The expression element is a Boolean expression. If the expression evaluates to true, then operator1 (then branch) is executed, otherwise operator2 (else branch) is executed. Then, control is transferred to the operator following the conditional.

Consider a code fragment of a program that determines the minimum value of two numbers:

(Program code fragment)

  • if (a > b) then
  • minDig:= b
  • minDig:= a;
  • writeln(minDig);

If the value of variable a is greater than the value of variable b, then the assignment operator will be executed in the then branch (minDig will receive the value of b), otherwise - in the else branch (minDig will receive the value of a), then the value of the minDig variable will be printed.

In a conditional statement, there can be only one statement after then and after else. Therefore, if you need to use more than one operator, then a compound operator is used.

Short form of the conditional statement

The short form of the conditional operator is written as follows:

  • if expression then
  • operator

If the expression evaluates to true, then the statement is executed, otherwise the transition to the next program statement occurs. So, in the following fragment of program code, if the number x turns out to be odd, then its value will be increased by 1 (i.e., it will become even), otherwise the transition to displaying the value of x on the screen occurs.

Operator is a programming language sentence that specifies a complete description of some action that needs to be performed. The main part of a Turbo Pascal program is a sequence of statements. The statement separator is a semicolon. All Turbo Pascal language operators can be divided into two groups: simple and structural.

Statements that do not contain any other statements are called simple. These include assignment, unconditional jump, procedure call, and the empty operator.

Assignment operator

Assignment operator (:=) instructs to execute the expression specified on its right side and assign the result to a variable whose identifier is located on the left side. The variable and expression must be of compatible type.

The assignment operator is executed as follows: first, the expression on the right side of the assignment is evaluated, and then its value is assigned to the variable specified on the left side of the operator.

For example, for the operator

Result:=A div B;

First, integer division of the variable's value is performed A to the value of the variable IN and then the result is assigned to a variable Result.

Examples of using the assignment operator:

A:= 8;

S:=A*IN;

Ostatok:= A mod B;

Ratio:= A / B;

Unconditional jump operator (go to)

Unconditional jump operator (go to) means “go to” and is used in cases where, after executing a certain statement, it is necessary to execute not the next one in order, but some other statement marked with a label.

Recall that a label is declared in the label description section and can contain both numeric and alphabetic characters.

When using the operator go to it must be remembered that label scope is only the block in which it is described. Transferring control to another block is prohibited.

Rules for using the unconditional jump operator. The use of unconditional transfers of control in a program is considered theoretically redundant and is subject to serious criticism, as it contributes to the creation of obscure and difficult to modify programs that cause great difficulties in debugging and maintenance. Therefore, minimal use of the operator is recommended go to subject to the following rules:

You should strive to use jump operators (if it seems impossible to do without them) to transfer control only downward (forward) through the program text; if it is necessary to transfer control back, loop operators should be used;

The distance between the label and the jump operator should not exceed one page of text (or the height of the display screen).

An example of using the unconditional jump operator:

label Mark; (in the label description section we described a label with the nameMetka}

begin (main program)

(main program statements)

(main program statements marked with a label)

Work order

    Study theoretical information on the topic: “Writing a program in Pascal using assignment operators and unconditional jump.”

    Receive an individual assignment from the teacher and develop a program in accordance with the task.

    Show the working program to the teacher.

    Answer security questions.

Control questions

    Basic elements of programming.

    Main characteristics of the program. Concepts of language, overlays, global and local blocks.

    Operators of the Pascal programming language. Assignment operator. Format, examples.

    Unconditional jump operator. Format, examples. Basic rules of use

Laboratory work No. 7

Writing a program in Pascal using conditional statements and the selection operatorCase

Goal of the work : formation of knowledge and skills in working with language operators. Acquiring skills in writing programs using assignment operators and unconditional jumps.

Brief theoretical information

Conditional statements

Conditional operators are designed to select one of the possible actions (operators) for execution depending on some condition (in this case, one of the actions may be empty, i.e. absent). The value of a logical expression is used as selection conditions.

There are two conditional statements in Turbo Pascal: if and case.

Conditional statement if

Condition operator if is one of the most popular means of changing the natural order of execution of program statements.

It can take one of the following forms:

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

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

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

Translated from English, these formats can be defined as:

    IF <условие> THAT <оператор1> OTHERWISE <оператор2>

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

Condition operator if is performed as follows. First, the expression written in the condition is evaluated. As a result of its calculation, a value of Boolean type is obtained.

In the first case, if the value of the expression is True(true), executed <оператор1>, indicated after the word then(translated as “that”). If the result of calculating the expression in the condition is False(false), then executed <оператор2> .

In the second case, if the result of the expression True, performed <оператор>, If False- operator immediately following the operator if. Operators if can be nested.

An example of a program fragment with an if conditional statement:

if Ch="N" then Password:= True

else Password:= False;

if Password = True then

if X = 100 then Write("Password and code are correct")

Writeln("Error in code");

In this example, the value of a character type variable is read from the keyboard Ch. Then the condition is checked WITHh=" N" . If it is fulfilled, then the variable Password boolean type is assigned a value True, if the condition is not met, False. Then the code value is read from the keyboard X. Next, the if statement checks the condition Passol = True. If it matters True, then the entered password is checked by the operator if X=100. If the condition X=100 has the meaning True, then the message “The password and code are correct” is displayed, and control in the program is transferred to the operator following the word end, if it matters False, the compound statement after the word is executed else, which displays the message “Error in code” on the video monitor screen and calls the standard procedure Halt(1) to stop the program.

Features of the operatorif. When using nested conditional statements, syntactic ambiguity may arise, for example:

if condition1 then if condition2 then<оператор1>else<оператор2>

The resulting ambiguity about which operator if belongs to part else <оператор2>, permitted by the fact that the function word else always associated (linked) with the closest function word in the text if, which is not yet associated with the function word else.

Because of this, you should be careful when writing nested conditional statements.

Example 1 . Write a program that calculates the quotient of two integers. Due to the fact that it is impossible to divide by zero, organize data entry control.

To control the input values ​​of the divisor, we use the conditional jump operator if ... then ... else.

The program text might look like this:

program Primer1;

A, B: integer;

Write("Enter the value of dividend A: ");

Write("Enter the value of divisor B: ");

if B=0 (Number input controlB}

then Writeln("Zero cannot be divided") (Condition met)

(Condition not met)

Result:= A / B;

Writeln("Quotient of numbers ",A," and ",B, " = ", Rezult);