The simplest operator that specifies the sequential execution of the operators included in it one by one.

It is used when the syntax of the Pascal language allows the use of only one operator, while the semantics require specifying a certain sequence of actions.

Example:

begin (exchange of variable values X and Y)

Z:=X;

X:=Y;

Y:=Z;

end;

Conditional operator

Conditional operators are designed to select one of two possible actions (operators) for execution depending on some condition (in this case, one of the actions may be empty, that is, absent). The value of a logical expression is used as the selection condition. The syntax diagram for the conditional statement is given below.

This operator is executed as follows. First, the expression after the function word is evaluated if . The result of the calculation must be of Boolean type. If the value of the expression is true , then the operator specified after the service word is executed then . If the result of evaluating the expression is false , the operator following the service word is executed else . If at the same time part of the conditional operator, starting with the word else , is missing, then control is immediately transferred to the operator following the conditional.

Examples of conditional statements:

1) if X< Y then

Max:=Y

else

Max:=X

2) if All_Correct then

Transpose(A,B,N)

3) if Color = Red then

begin

X:= cos(Y);

Y:= alpha+beta;

Color:=Yellow

else begin

X:= Sin(Y);

Color:= Red

end;

When using nested conditional statements, syntactic ambiguity can arise, as illustrated by the following diagram:

if Expr1 then if Expr2 then Stmt1 else Stmt2

In the above statement, the part else Stmt 2 can be interpreted as belonging to or "external" operator if Expr 1 . . ., or nested operator if Expr 2 then . . .. This ambiguity is resolved by the following interpretation of this construction:

if Expr1 then

begin

if Expr2 then

Stmt1

else

Stmt2

In other words, the function word else always associated with the closest function word in the text if , which is not yet associated with the function word else.

Care should be taken when writing nested conditional statements.

Variant operator

This operator is a generalization of the conditional operator from the previous section for the case of an arbitrary number of alternatives. Specifically, you can associate different values ​​of a certain expression with their corresponding operators. The simplest example The variant operator is given below.

saze Color of

Red: X:= Y+2;

Yellow: X:= Y-2;

Green: X:= Y

Assuming that Color is a variable of an enumerated type, this statement will be executed as follows.

First, the current value of the variable is calculated Color . This value is then matched (compared) with the constants written before the operators. If the value of a variable matches one constant, the statement “marked” with this constant will be executed. This completes the execution of the variant statement. If the variable value Color does not match any constants, then this operator does not perform any action. In order to specify some actions in case of such a mismatch, you can use the alternative else , for example:

saze (K+l)*2 of

2: Add(A, B);

4: Multiply (A,B);

0: Substract(A, B)

else

Writeln("Error!")

Operator following the function word else , will be executed if the value of the expression (K+1) *2 does not coincide with any of the constants 2,4,0.

In addition to single constants, variant operator alternatives can contain lists and/or ranges of values, which in this case must be separated by the "," (comma) character, for example:

case Switch of

1. .2: Prod;

3,4,10..20: Proc2;

5, b: РгосЗ

else

Proc4

In the last example, the procedure statement Proc2 will be executed when the variable Switch will have one of the following values: 3,4,10,11,12, . . ., 19.20.

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

1. The value of the "switch" expression written after the function word saze must belong to a discrete type; for an integer type they must be in the range -32768. .32768.

2. All constants preceding alternative operators must be of a type compatible with the type of the expression.

3. All constants in alternatives must be unique within the variant operator (that is, repetitions of constants in alternatives are not allowed); ranges must not overlap and must not contain constants specified in this or other alternatives.

Finally, here is a syntax diagram for the variant operator.

Variant operator

Alternative

Note that the language syntax assumes one statement for each alternative; If you need to specify several statements, you should group them into a compound statement. At the same time the branch else allows a sequence of statements separated by ";" (semicolon).

Loop operator with precondition

Syntax diagram for of this operator as follows:

This structure statement specifies repeated execution of the statement it contains. Before each next execution of the internal operator, the value of the Boolean expression is checked, which

serves as a repetition criterion: if this expression has a meaning true , then the next iteration is performed; otherwise (the value of the expression is false ) execution of the loop operator ends. If the expression has a meaning from the very beginning false , then the loop will not be executed even once.

Examples of a loop operator with a precondition include:

In the last example, an "endless" loop is specified, since the expression after the service word while identically equal true . Termination of this loop can occur, for example, as a result of moving along a label outside the loop statement.

This operator is similar to the previous operator (a loop with a precondition) and differs from it, firstly, in that the condition is checked AFTER the execution of the next iteration (thus guaranteeing at least one execution of the loop), and, secondly, in that the criterion termination of the loop is the equality of the expression to a constant true ; if there is an expression false , then the cycle repeats.

For example, a cycle like

repeat

Procl(X,Y+i);

i:=i-1

until i = 0;

will be executed UNTIL i will not be equal to zero.

Below is a syntax diagram for a loop with a postcondition.

Loop operator with postcondition

Please note that the syntax is while -loop allows only one statement in the loop body, while repeat -loop can contain a sequence of statements.

Let's give two more examples repeat cycles.

repeat

K := I mod J;

I:= J;

J:= K ;

until J = 0;

repeat

Write ("Enter an integer; ") ;

Readln(i);

Process(i)

until (i< 0) and (i > 9);

Loop statement with parameter

Such statements are typically used when the number of times a loop can be repeated can be determined before it begins. In addition, parameterized loops allow you to specify automatic change values ​​of some variable and use of this value in successive iterations. More specific, this option The loop operator defines:

a) the range of changes in the values ​​of the control variable and, at the same time, the number of repetitions of the operator contained in the body of the loop;

b) the direction of change in the value of the variable (increase or decrease);

c) the actual actions performed at each iteration (loop body operator).

The following simple example illustrates the use of a loop with a parameter.

for i:=1 to 10 do M[i]:=i*2

IN in this example a tenfold repetition of the assignment operator is specified, and the control variable i sequentially takes the values ​​1, 2, . . ., 9,10.

The range of values ​​of the control variable can be specified by expressions that are evaluated ONCE before executing the loop:

for j:=X+2 downto X-2 do

begin

M:=Func(A,B);

Proc(M,j)

In this example, the variable value j decreases sequentially from the initial value X+2 to the final value x-2.

Loop statement with parameter

Range

The following restrictions apply to the use of a control variable:

1. The control variable must be a simple variable described in the current block.

2. The control variable must be of a discrete type.

3. The start and end values ​​of the range must be of a type compatible with the type of the control variable.

4. In the body of the loop, explicit changing of the value of the control variable (for example, by an assignment operator) is prohibited.

5. After the statement completes, the value of the control variable becomes undefined, unless the execution of the loop statement was interrupted by a jump statement. (However, practice with the system Turbo Pascal shows that in fact the last used value of the control variable is retained even when exiting the loop normally).

A statement that is contained in the statement body for , is executed once for each value in the range between the start and end values. The control variable is always initialized to an initial value. In case of using a function word to the value of the control variable increases by one with each repetition. If the initial value exceeds the final value, then the body of the statement for operator will not be executed. When a loop statement uses a function word downto , the value of the control variable decreases by one with each repetition. If the initial value in such an operator is less than the final value, then the operator contained in the body of the loop operator will not be executed even once.

Taking into account all that has been said, we can imagine the semantics of this loop operator as follows. Operator

for V:= Expr1 to Expr2 do Body;

is equivalent to the operator:

begin

Temp1:= Expr1;

Temp2:= Expr2;

if Temp1<= Temp2 then

begin

V:= Temp1;

Body ;

while V<>Temp2 do

begin

V:= Succ(V);

Body;

end;

end;

end;

Similarly, the loop operator for V:= Expr1 downto Exp2 do Body; is equivalent to the operator:

begin

Temp1:= Expr1;

Temp2:= Expr2,

if Temp1 >= Temp2 then

begin

V:= Temp1;

Body ;

while V<>Temp2 d o

begin

V:=Pred(V);

Body;

end;

end;

end ;

where Temp 1 and Temp 2 - auxiliary variables, the type of which coincides with the main type of the variable V and which do not appear elsewhere in the program.

Here are examples of a loop operator with a parameter:

1) for I:= 2 to 63 do

if Data[I] > Max then Max:- Data[I]

2) for I:= 1 to 10 do

for J:= 1 to 10 do begin

X:= 0;

for K := 1 to 10 do

X:- X + Mat1*Mat2;

Mat := X;

end;

3) for Day:= Monday to Friday do

Calculate_Profit(Day);

Empty operator

An empty operator is, in a sense, a paradoxical construction, since, firstly, it does not have a “graphic” outline, and, secondly, it does not perform any actions. The need to introduce such a concept is dictated primarily by syntactic reasons. For example, suppose in a program you need to transfer control to the end of a compound statement. This can be done using the unconditional jump operator. But by definition, a label must necessarily precede some operator. Thus, strictly speaking, it is impossible to transfer control to the end of any composite structure. However, if we assume that the label in this case precedes the empty statement, then the solution to this problem may look like this:

begin

goto Out;

Out :

Let's consider another practically useful case of using the concept empty operator. Language syntax Pascal defines the character ";" (semicolon) as statement separator. Thus, the last statement, for example, in a compound statement, should not end with this symbol, since it is not followed by an operator, but by a service word end:

begin

S1; S2; ...; SN

However, if we assume that between the last statement SN and a service word end If there is an empty operator, then the following form of notation becomes acceptable:

begin

S1; S2; ...; SN;

which in some cases is more preferable.

The empty operator is also convenient to use in cases where, for one reason or another, it is necessary to organize

some compound statement that does not contain a single operator, for example:

repeat until KeyPressed;

Here the loop body does not contain a single statement, which the language syntax does not allow. In this case, the loop is considered to contain one empty statement. The above example can be conveniently used to delay program execution while waiting for any key to be pressed (function KeyPressed -standard function language Turbo Pascal - returns value true when you press an arbitrary key and false otherwise).

In conclusion, we note that the introduction of the concept of an empty operator makes quite exotic constructions of the form admissible:

1) begin S1;;;;;S2; end

2) if Cond then begin end

else while true do;

3) if Cond then ;

where S 1, S 2 are operators, Cond - some expression of Boolean type.

This lesson looks at the conditional operator in Pascal ( if). Explains how to use multiple conditions in one construct ( AND And OR). Examples of working with an operator are considered

We remind you that this site does not pretend to provide a complete presentation of information on the topic. The purpose of the portal is to provide the opportunity to assimilate material based on ready-made solved examples on the topic “Language” Pascal programming» with practical tasks to reinforce the material. The Pascal tasks presented on the site are arranged sequentially as their complexity increases. The website can be used by teachers and lecturers as an auxiliary visual aid.

Before considering this topic, linear algorithms in Pascal were mainly used, which are typical for very simple problems when actions (operators) are performed sequentially, one after another. More complex algorithms involve the use of a branching construct.

Conditional operator block diagram:

The conditional statement in Pascal has the following syntax:

Abridged version:

if condition then statement;

Full version:

if condition then statement else statement;

The conditional operator in Pascal - if - serves to organize the progress of a task in such a way that the sequence of execution of operators changes depending on some logical condition. A logical condition can take one of two values: either true or false, respectively, it can be either true or false.

Compound operator

If, under a true condition, it is necessary to execute several statements, then them according to the rules Pascal language must be enclosed in a block, starting with the function word begin and ending with the function word end . Such a block is usually called operator brackets, A this designcompound operator:

Operator brackets and compound operator in Pascal:

if logical expression then begin statement1; operator2; end else begin statement1; operator2; end;

Translation from English of the condition operator will make it easier to understand its use:

IF THEN ELSE
IF THAT OTHERWISE


The condition (in a logical expression) uses relational operators.
Consider Pascal's list of relational operators:

  • more >
  • less
  • greater than or equal to in Pascal >=
  • less than or equal to in Pascal
  • comparison in Pascal =
  • not equal in Pascal

Example: find the largest of two numbers

Option 1 Option 2


Understand the work in detail you can use the conditional operator in Pascal by watching the video tutorial:

Example: calculate the value of the variable y using one of two branches

Show solution:

var x,y:real; begin writeln("enter x"); read(x); if x>0 then y:=ln(x) else y:=exp(x); writeln ("y=", y:6:2) (the resulting number will occupy 6 positions and will have 2 decimal places) end.

Notice how y is output in this example. When withdrawing type variables in pascal, you can use the so-called formatted output, or notation with two colons:
y:6:2
- the number after the first colon (6) indicates how many characters the number will occupy when displayed on the screen
- the number after the second colon (2) indicates how many decimal places there are real number will be displayed

Thus, using such notation in pascal practically allows you to round to hundredths, thousandths, etc.

Task 0. Calculate the value of the variable y using one of two branches:

Task 1. Two numbers are entered into the computer. If the first is greater than the second, then calculate their sum, otherwise - the product. After this, the computer should print the result and the text PROBLEM SOLVED

Task 2. The dragon grows three heads every year, but after it turns 100 years old, only two. How many heads and eyes does a dragon have? N years?

Logical operations in Pascal (in logical expression)

When you need to use a double condition in Pascal, you will need logical operations.

  • Logical operation AND (And), placed between two conditions, says that both of these conditions must be met at once (must be true). The logical meaning of the operation is “conjunction”.
  • Placed between two conditions, the sign OR (OR) says that it is sufficient if at least one of them is satisfied (one of the two conditions is true). The logical meaning of the operation is “disjunction”.
  • In Pascal XOR - a sign of a logical operation that has the meaning of “strict disjunction” and indicates that it is necessary that one of the two conditions be fulfilled (true), and the other not satisfied (false).
  • Logical operation NOT before a logical expression or variable it means “negation” or “inversion” and indicates that if a given variable or expression is true, then its negation is false and vice versa.

Important: Each simple condition must be enclosed in parentheses.

Example: Let's look at examples logical operations in logical expressions in Pascal

1 2 3 4 5 6 7 8 var n: integer ; begin n: = 6 ; if (n>5 ) and (n<10 ) then writeln ("истина" ) ; if (n>7 ) or (n<10 ) then writeln ("истина" ) ; if (n>7 )xor (n<10 ) then writeln ("истина" ) ; if not (n>7) then writeln("true"); end.

var n:integer; begin n:=6; if (n>5) and (n<10) then writeln("истина"); if (n>7) or (n<10) then writeln("истина"); if (n>7)xor(n<10) then writeln("истина"); if not(n>7) then writeln("true"); end.

Example: The company recruits employees from 25 to 40 years of age inclusive. Enter the person’s age and determine whether he is suitable for this company (display the answer “suitable” or “not suitable”).
Peculiarity: we need to check whether two conditions are met simultaneously.

An operator is an indivisible element of a program that makes it possible to perform certain algorithmic actions. The difference between an operator and other elements is that it always implies some kind of action. In Pascal, operators consist of function words. Operators used in a program are separated from each other and from other program elements by the symbol (;). All Pascal operators can be roughly divided into two groups:

  1. simple;
  2. structured.

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

  • assignment operator (:=);
  • procedure statement;
  • unconditional jump operator (GOTO).

Structured statements are operators that contain other operators. These include:

  • compound operator;
  • conditional operators (IF, CASE);
  • loop operators (FOR, WHILE, REPEAT);
  • join operator (WITH).

Simple Operators

Procedure operator

Procedure operator serves to call a procedure.

Format: [procedure_name] (list of call parameters);

A procedure statement consists of a procedure identifier, immediately followed by a list of call parameters in parentheses. Pascal has procedures without parameters. In this case, when called, there is no list of parameters. Execution of a procedure statement leads to the activation of the actions described in its body. There are two types of procedures in Pascal:

  • Standard ones, which are described in the language itself and are part of the language;
  • User procedures that are created by the user.

To call standard procedures, you must connect in the USES section of the module (library) name, where this procedure is described. A number of procedures located in the SYSTEM module are always connected to the program automatically and their connection in the USES section is not necessary. Standard Pascal procedures are READ, WRITE, REWRITE, CLOSE, RESET.

READ ([file_variable], [input_list])

READ(x,y)

User procedures (non-standard) must be created before their use in the program and are located either in the description section of the program itself, or in separate program units of the module. If the procedure is in a module, then the name of that module must be mentioned in the USES application.

Unconditional GOTO operator

Format: GOTO [label];

GOTO- reserved word in Pascal language. [label] is an arbitrary identifier that allows you to mark a certain program statement and later refer to it. In Pascal, it is possible to use unsigned integers as labels. The label is placed before and separated from the marked operator (:). One statement can be marked with several labels. They are also separated from each other (:). Before using a label in the statement section, it must be described in the LABEL section (description section).

The GOTO action transfers control to the appropriate marked statement. When using tags, you must follow the following rules:

  • the label must be described in the descriptions section and all labels must be used;
  • if integers are used as labels, they are not declared.

Contradicts the principles of technology structured programming. Modern programming languages ​​do not include such an operator, and there is no need to use it. Besides, in modern computers The so-called conveyor method is used. If an unconditional jump operator is encountered in a program, then such an operator breaks the entire pipeline, forcing it to be created anew, which significantly slows down the computational process.

Structured statements

IF condition statements

The conditional operator is used in the program to implement the algorithmic structure - branching. In this structure, the computational process can continue in one of the possible directions. The choice of direction is usually carried out by checking some condition. There are two types of branching structures: fork and bypass structures.

In the Pascal language, the conditional IF operator is a means of organizing a branching computational process.

Format: IF [boolean_expression] Then [operator_1]; Else [operator_2];

IF, Then, Else are function words. [operator_1], [operator_2] - ordinary operations of the Pascal language. The Else part is optional (may be missing).

The IF statement works like this: It first checks the result of a Boolean expression. If the result is TRUE, then [statement_1] following the Then function word is executed, and [statement_2] is skipped. If the result is FALSE, then [statement_1] is skipped and [statement_2] is executed.

If the Else part is missing, then the IF statement is not in full form:

IF [boolean expression] Then [operator];

In this case, if the result is True (TRUE), then the [statement] is executed; if False (FALSE), then control is transferred to the statement following the IF statement.

There are 2 numbers A and B. Find the maximum number.

Compound operator

A compound statement is a sequence of arbitrary operations in a program, enclosed in so-called operator brackets (Begin-End).

Format: Begin [operators]; End;

Compound statements allow a group of statements to be represented as a single statement.

CASE selection statement

Designed to implement multiple branches, since the IF operator can implement only two directions of the computational process, it is not always convenient to use it to implement multiple branches. Multiple branching is implemented by the CASE statement.

Format: CASE [select_key] OF

[selection_constant_1]:[operator_1];

[selection_constant_2]:[operator_2];

[selection_constant_N]:[operator_N];

ELSE [operator];

CASE, OF, ELSE, END - function words. [select_key] is a parameter of one of the ordinal types. [selection_constants] - constants of the same type as the selection key that implement selection. [operator_1(N)] is an ordinary operator. ELSE may be missing.

The selection operator works as follows: before the operator operates, the value of the selection key parameter is determined. This parameter can either be expressed as a variable in the program or in some other way. Then the selection key parameter is sequentially compared with the selection constant. If the value of the selection key matches one of the selection constants, the operator following this constant is executed, and all other operators are ignored. If the selection key does not match any of the constants, the statement following Else is executed. Often Else is optional and if the selection key does not match any of the selection constants and in the absence of Else, control is transferred to the statement following the CASE statement.

The CASE statement does not have the explicit conditional checking that is typical for the IF statement. At the same time, the comparison operation is performed implicitly. CASE introduces dissonance into a Pascal program, since this statement ends with the service word End, which does not have a paired Begin.

Create an algorithm and program for a problem simulating the operation of a traffic light. When you enter the symbol of the first letter of the traffic light colors, the program should display a message about the corresponding color and actions.

The program works as follows: using the Read procedure, the letter symbol of the traffic light color is entered from the keyboard. If the letter ‘z’ corresponding to the green color is entered, then in the CASE statement the value entered in the selection list will find the selection constant ‘z’ and the message “Green color, movement is allowed” will be displayed. When you enter the symbol of the letters 'k' and 'zh', similar messages will be displayed. If you enter any other character, the message “Traffic light does not work” will be displayed, because in this case the Else part of the CASE statement works.

Loop statements

Cyclic algorithmic structure a structure in which some actions are performed several times is considered. There are two types of loop structures in programming: the loop with a parameter and the iterative loop.

In a cycle with a parameter there are always so-called cycle parameters: X, X n, X k, ∆X. Sometimes a loop with a parameter is called a regular loop. A characteristic feature is that the number of loops and repetitions can be determined before the loop is executed.

In an iterative loop, it is impossible to determine the number of loops before executing it. It is executed as long as the loop continuation condition is satisfied.

The Pascal language has three operators that implement cyclic computational structures:

  • counting operator FOR. It is intended to implement a loop with a parameter and cannot be used to implement an iterative loop;
  • loop operator with WHILE precondition;
  • loop operator with REPEAT postcondition.

The last two are focused on implementing an iterative loop, but they can also be used to implement a loop with a parameter.

FOR operator

Format: FOR [loop_parameter] := [n_z_p_ts] To [k_z_p_ts] Do [operator];

FOR, To, Do are function words. [cycle_parameter] - cycle parameter. [n_z_p_ts] - the initial value of the cycle parameter. [k_z_p_ts] - final value of the cycle parameter. [operator] - arbitrary operator.

The loop parameter must be an ordinal variable. The start and end values ​​of the loop parameter must be of the same type as the loop parameter.

Let's consider the operator's work using its algorithm:

At the first step, the value of the cycle parameter takes [n_z_p_ts], then the cycle parameter is checked to be less than or equal to [k_z_p_ts]. This condition is the condition for continuing the loop. If executed, the loop continues its operation and the [statement] is executed, after which the loop parameter is increased (decreased) by one. Then, with the new value of the loop parameter, the condition for continuing the loop is checked. If it is fulfilled, then the actions are repeated. If the condition is not met, then the loop stops running.

The For operator is significantly different from similar operators in other programming languages. The differences are as follows:

  • body of the For operator. The statement may not be executed even once, since the loop continuation condition is checked before the loop body;
  • the cycle parameter change step is constant and equal to 1;
  • The body of the loop in the For statement is represented by one statement. If the action of the loop body requires more than one simple statement, then these statements must be converted into one compound statement using operator brackets (BEGIN-END);
  • A loop parameter can only be an ordinal variable.

Example of using the FOR operator: create a table for converting rubles to dollars.

WHILE statement (loop statement with precondition)

Format: WHILE [condition] Do [operator];

WHILE, Do - function words. [condition] - expression of logical type. [operator] - ordinary operator.

;

The While statement works as follows: first, the result of the logical condition is checked. If the result is true, then the statement is executed, after which it returns to checking the condition with the new value of the parameters in the logical expression of the condition. If the result is false, then the loop is terminated.

When working with While, you need to pay attention to its properties:

  • the conditions used in While are the loop continuation condition;
  • in the body of the loop, the value of the parameter included in the condition expression always changes;
  • The While loop may not execute even once, since the condition check in the loop continuation is performed before the loop body.

REPEAT statement (loop statement with postcondition)

Format: REPEAT [cycle_body]; UNTIL [condition];

The REPEAT statement works as follows: first, the statements in the body of the loop are executed, after which the result is checked for the logical condition. If the result is false, then it returns to executing the statements of the next loop body. If the result is true, then the operator exits.

The Repeat operator has the following features:

  • in Repeat, the loop termination condition is checked and if the condition is met, the loop stops working;
  • The body of the loop is always executed at least once;
  • the parameter for checking the condition is changed in the body of the loop;
  • The loop body statements do not need to be enclosed in operator brackets (BEGIN-END), while the role of operator brackets is performed by Repeat and Until.

Calculate y=sin(x), where xn=10, xk=100, step is 10.

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 absent). The value of a logical expression is used as selection conditions. Turbo Pascal has two conditional statements: if and case.

Conditional statement if

The if conditional statement can take one of the following forms:

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

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

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

The if conditional statement is executed 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, then<оператор1>, specified after the word then. If the result of evaluating the expression in the condition is False, then<оператор2>. In the second case, if the result of the expression Tgue, then<оператор>, if False, the statement immediately following the if statement is executed. According to the rules, each branch can contain either one executable statement or several combined into a compound statement. Semicolon before Else not installed.

case selection operator

If one operator if can provide a choice between two alternatives, then the selection operator case allows you to make a choice from an arbitrary number of available options.

case<выражение-селектор>of

<список1>: <оператор1>;

<список2>: <оператор2>;

<списокN>: <операторN>;

The case statement 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 current selector value, the statement following the word "else" is executed. If the word "else" is missing, the operator following the word "end" is activated, i.e. the first operator abroad case.

A selector expression is a simple variable of integer, character, enumeration, or boolean types, depending on the value of which a decision is made;

A list of selection constants consists of an arbitrary number of values, or ranges, separated by commas. The type of the constants must match the type of the selector;

The specified format assumes the use of one statement for each alternative, but if necessary, you can specify multiple statements by grouping them into a compound statement.

Branch Else is optional, and unlike the if statement, it can be preceded by a semicolon.

Repeat operators

If there is a need to repeatedly execute some statements in a program, then repeat (loop) operators are used. In the Pascal language, there are three types of loop operators: while, repeat, for.

while statement

The while operator is called a loop operator with Precondition because the execution condition of the loop body is checked at the very beginning of the statement.

while<условие продолжения повторений>do

<тело цикла>;

Condition – logical expression. Loop body – simple or compound operator. A compound operator is used in cases where the body of a loop consists of 2 or more operators.

Before each execution of the loop body, the value of the condition expression is calculated. If the result is True, the body of the loop is executed and the condition expression is evaluated again. If the result is False, the loop exits and moves to the first statement immediately following the body of the loop.

repeat operator

The repeat operator implements a loop with postcondition . A loop with a postcondition will always be executed at least once.

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

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

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

until<условие окончания цикла>;

The statements between the words repeat and until are the body of the loop. First, the body of the loop is executed, then the condition for exiting the loop is checked. If the result of the logical expression is False, then the body of the loop is activated again; if the result is True, the loop exits.

Repeat operator for

This is an operator with a known number of repetitions. This repeat operator is often called a parameterized loop operator because the number of repetitions is specified by a variable called loop parameter , or control variable .

The for repeat operator can be represented in two formats:

for<параметр цикла> := to do<тело цикла>;

for<параметр цикла> := downto do<тело цикла>;

Where<параметр цикла>is a variable of integer, character, logical or enumerated types;

SI and S2 are expressions that determine, respectively, the initial and final values ​​of the cycle parameter;

for ... do - loop header;

The body of the loop can be simple or composite operator The for operator ensures that the body of the loop is executed until all values ​​of the loop parameter from the start to the end are enumerated.

Command action. The loop parameter is assigned the value of the expression S1. If it is less than or equal to the value of expression S2, then the body of the loop is executed. After this, the value of the parameter is automatically increased by one and it is again compared with the value of expression S2, etc. When the value of the parameter becomes greater than the value of expression S2, the next statement after the loop is executed.

The step of changing the loop parameter for the for...to...do operator is +1, and for the for...downto...do operator is -1.

Self-test questions:

    Assignment operator format. Is it permissible to use quantities? different types in arithmetic expression?

    What is the difference between the Read input statement and the Readln statement?

    Specify data output formats.

    What types of branching are implemented in Turbo Pascal?

    What are branches used for? Give examples.

    Two forms of writing the conditional operator If.

    Recording format for a nested If statement.

    Case selection statement notation format?

    In what cases is the compound Begin...end operator used?

    How are branched algorithms depicted in flowcharts?

    What is a cycle?

    What types of loops are implemented in Turbo Pascal?

    What is a loop body?

    In what case is the body of a loop enclosed in operator brackets begin...end?

    What is the difference between the while and repeat statements?

    In what cases is it preferable to use the repeat operator for to organize loops? What is written in the header of this statement?

    How does a for loop statement describe the direction in which the value of a loop parameter changes?

"fork".
Branching out is an algorithm in which one of several is selected possible options computing process. Each such path is called branch of the algorithm.

A sign of a branching algorithm is the presence of condition checking operations. The most common way to test a condition is to use the if statement.

if can be used in full or incomplete fork form.

In case of incomplete fork if Condition true, then BlockOperations1 executed if Condition false, then BlockOperations1 is not executed.

In case of a complete fork if Condition true, then true BlockOperations1 , otherwise executed BlockOperations2 .

BlockOperations may consist of one operation. In this case, the presence of curly braces demarcating the block is optional.

Example in C:

1
2
3
4
5
6
7
8
9
10
11
12
13
14


#include
int main()
{
int k; // declare an integer variable k
printf("k= " ); // display a message
scanf("%d" , &k); // enter variable k
if (k >= 5) // if k>5
printf("%d >= 5" , k); // print "VALUE >= 5"
else // otherwise
printf("%d< 5" , k); // print "VALUE< 5"
getchar(); getchar();
return 0;
}


Execution result

The if statement can be nested.

Example in C:

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

#define _CRT_SECURE_NO_WARNINGS // to be able to use scanf
#include
#include
int main() (
int key;
system("chcp 1251" );
system("cls" ); // clear the console window
printf();
scanf("%d" , &key);
if (key == 1) // if key = 1
printf( "\nFirst item selected"); // display a message
else if (key == 2) // otherwise if key = 2
printf( "\nSecond item selected"); // display a message
else // otherwise
printf(); // display a message
getchar(); getchar();
return 0;
}

Execution result





When using a nested form of an if statement, the else option is associated with the last if statement. If you want to link an else option to a previous if statement, the inner conditional statement is enclosed in curly braces:

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

#define _CRT_SECURE_NO_WARNINGS // to be able to use scanf
#include
#include // to use the system function
int main() (
int key; // declare the whole variable key
system("chcp 1251" ); // switch to Russian in the console
system("cls" ); // clear the console window
printf( "Enter item number, 1 or 2: ");
scanf("%d" , &key); // enter the value of the key variable
if (key != 1) ( // if key is not equal to 1
if (key == 2) // if key is 2
printf( "\nSecond item selected"); // message output
} // if key is neither 1 nor 2, then nothing is output
else // otherwise if key is 1
printf( "\nFirst item selected"); // message output
getchar(); getchar();
return 0;
}


Execution result





Ternary operations

Ternary conditional operator has 3 arguments and returns its second or third operand depending on the value of the Boolean expression given by the first operand. Ternary operator syntax in C language

Condition? Expression1: Expression2;


If fulfilled Condition, then the ternary operation returns Expression1, otherwise - Expression2 .

Ternary operations, like conditional operations, can be nested. Parentheses are used to separate nested operations.

The above example using ternary operators can be represented as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#define _CRT_SECURE_NO_WARNINGS // to be able to use scanf
#include
#include // to use the system function
int main() (
int key; // declare the whole variable key
system("chcp 1251" ); // switch to Russian in the console
system("cls" ); // clear the console window
printf( "Enter item number, 1 or 2: ");
scanf("%d" , &key); // enter the value of the key variable
key == 1 ? printf( "\nFirst item selected") :
(key == 2 ? printf( "\nSecond item selected") :
printf( "\nThe first and second items are not selected"));
getchar(); getchar();
return 0;
}

Switch statement (multiple choice statement)

The if statement allows you to choose between only two options. In order to select one of several options, you must use a nested if statement. For the same purpose, you can use the switch branch operator.

General recording form

switch (IntegerExpression)
{
case Constant1: BlockOperations1;
break ;
case Constant2: BlockOperations2;
break ;
. . .
case Constant: BlockOperationsn;
break ;
default: DefaultOperationBlock;
break ;
}

The switch statement is executed as follows:

  • calculated IntegerExpression in parentheses of the switch statement;
  • the resulting value is compared with the labels ( Constants ) in case options, the comparison is performed until a label corresponding to the evaluated value of the integer expression is found;
  • performed BlockOperations corresponding label case ;
  • if the corresponding label is not found, then DefaultOperationBlock , described in the default option.

The default alternative may not be present, in which case no action will be taken.
Option break; exits the switch statement and moves to the next statement. If the break option is absent, all statements will be executed, starting with the one marked with this label and ending with the statement in the default option.

Constants in case options must be of integer type (can be characters).