Contacts

10 logical values ​​of the expression operation. Logical values, operations, expressions. (Grade 10). Programming Branches in Pascal

Statement (judgment) - It is a declarative sentence that affirms or denies something. Any statement can be said to be true or false. For example:

“Ice is the solid state of water” is a true statement.

“A triangle is a geometric figure” is a true statement.

“Paris is the capital of China” is a false statement.

6 < 5 - ложное высказывание.

Logical values: concepts expressed by words: TRUE, FALSE (true, false). Consequently, the truth of statements is expressed through logical quantities.

Logical constant: TRUE or FALSE.

Boolean variable: a symbolically designated logical value. Therefore, if it is known that A, B, X, Y and etc. - variable logical quantities, this means that they can only take the values ​​TRUE or FALSE.

Boolean expression- simple or complex statement. A complex statement is constructed from simple ones using logical operations (connections).

Logical operations. In mathematical logic, five basic logical operations are defined: conjunction, disjunction, negation, implication, equivalence. The first three of them are complete system operations, As a result, other operations can be expressed through them (normalized). In computer science, these three operations are commonly used.

Conjunction(logical multiplication). In Russian, it is expressed by the conjunction I. In mathematical logic, the signs are used & or . Conjunction is a two-place operation; is written as: A IN. The value of such an expression will be FALSE if the value of at least one of the operands is false.

Disjunction ( logical addition). In Russian, this connective corresponds to the conjunction OR. In mathematical logic it is denoted by the sign v. Disjunction is a two-place operation; is written as: A v IN. The value of such an expression will be TRUE if the value of at least one of the operands is true.

Negation. In Russian, this connective corresponds to the particle NOT (in some statements the phrase “it’s not true that...” is used). Negation is a unary (one-place) operation; is written as: A or .

Logical formula (logical expression) - a formula containing only logical quantities and signs of logical operations. The result of a Boolean formula is TRUE or FALSE.

Example 1. Consider the complex statement: “The number 6 is divisible by 2, and the number 6 is divisible by 3.” Present this statement in the form of a logical formula. Let us denote by A a simple statement “the number 6 is divisible by 2”, and through IN a simple statement “the number 6 is divisible by 3.” Then the corresponding logical formula looks like: A& IN. Obviously, its meaning is TRUE. Example 2. Consider the complex statement: “In the summer I will go to the village or on a tourist trip.”


Let us denote by A a simple statement “in the summer I will go to the village”, and through IN- a simple statement “in the summer I will go on a tourist trip.” Then the logical form of the complex statement has the form

Example 3. Consider the statement: “It is not true that 4 is divisible by 3.”

Let us denote by A the simple statement “4 is divisible by 3.” Then the logical form of the negation of this statement has the form A

The rules for performing logical operations are reflected in the following table, which is called the truth table.

The sequence of operations in logical formulas is determined by the precedence of operations. In descending order of precedence, logical operations are arranged as follows: negations, conjunction, disjunction. In addition, the order of operations is affected by parentheses that can be used in Boolean formulas.

Applications of mathematical logic in the basic course

Mathematical logic in databases. When studying a basic computer science course, students first encounter elements of mathematical logic in the topic “Databases” (DB). In relational databases, logical values ​​are fields of logical type. The Boolean type is used along with other field types, and students should learn to distinguish it.

The first concept of a logical quantity can be given as an answer to an alternative question. For example: “Is this book available in the library?” or “Has the applicant entered the university,” or “Is it raining outside?” and so on. The answers to such questions can only be “yes” or “no.” Synonyms are “true”, “false”; "true", "false". If a table field will accept only such values, then it is assigned a Boolean type.

For example, the OPTIONS relational database contains information about students' attendance in three electives: geology, floriculture, and dance. In relational language, its structure is described as follows:

OPTIONALS (STUDENT. GEOLOGY, FLORICULTURE, DANCE)

The fields GEOLOGY, FLORICULTURE and DANCE will be of Boolean type. A TRUE value for each field indicates that the student is attending that elective, and a FALSE value indicates that the student is not attending.

Boolean expressions are used in database queries as search terms. Logical expressions are divided into simple and complex. Simple expressions always use only one table field and do not use logical operations. Complex logical expressions use logical operations. A simple Boolean expression is either the name of a Boolean field or attitude(in mathematics they say “inequality”). Relations for numerical quantities retain the meaning of mathematical inequalities; When calculating relations for symbolic quantities, lexicographic order is taken into account; dates are compared in order of their calendar sequence.

The main problem is to teach students to formally represent search terms in the form of logical expressions. For example, from the phrase “find all books above the fifth shelf” you need to move to a logical expression: SHELF > 5; or the condition “select all those who fail in physics” is presented in the form: PHYSICS< 3; или «выбрать все дни, когда шел дождь» ОСАДКИ = «дождь».

Particular attention should be paid to the use of Boolean fields in search conditions. They are not usually treated with relationships. A Boolean field itself carries a Boolean value: “true” or “false”. For example, the condition “select all students attending dances” will be represented by a single logical field name DANCES.

Complex logical expressions contain logical operations. Three basic operations of mathematical logic are considered: conjunction (AND), disjunction (OR), negation (NOT).

Usually, when explaining this issue, the teacher starts from the semantic meaning of statements in Russian containing the conjunctions AND, OR, and the particle NOT. For example, the statement: “Today there will be a test in algebra AND physics” is true if both tests take place and false if at least one does not take place. Another statement: “Today there will be a test in algebra OR physics” will be true if at least one test takes place. And finally, the statement: “There will NOT be a test today” is true if there is no test, that is, if the statement that there will be a test today turns out to be false. From such examples, the teacher draws conclusions about the rules for performing logical operations: If A and B - logical values, then the expression

A and B true only if both operands are true;

A or IN false only if both operands are false;

Not A changes the value of a logical value to the opposite: not true - false; not a lie - the truth.

A discipline called mathematical logic is directly related to programming. The basis of mathematical logic is the algebra of logic, or propositional calculus. A statement is any statement that can be clearly stated to be true or false. For example, “The Moon is a satellite of the Earth” is true; “5 > 3” is true; “Moscow is the capital of China” is false; "1 = 0" is false. True or false are logical values. The logical meanings of the above statements are clearly defined; in other words, their values ​​are logical constants. The logical value of the inequality x< 0, где х - переменная, является переменной величиной. В зависимости от значения х оно может быть либо истиной, либо ложью. В связи с этим возникает понятие логической переменной.Основы формального аппарата математической логики создал в середине XIX в. английский математик Джордж Буль. В его честь исчисление высказываний называют булевой алгеброй, а логические величины - булевскими.Одиночные высказывания могут быть объединены в составные логические формулы с помощью логических операций.Имеются три основные логические операции: отрицание, конъюнкция (логическое умножение) и дизъюнкция (логическое сложение).Операция отрицания обозначается в математической логике значком ¬ и читается как частица не. Это одноместная операция.Например, ¬ (x = у) читается «не (х равно y)». В результате получится истина, если х не равно у, и ложь, если х равно у. Отрицание изменяет значение логической величины на противоположное.Операция конъюнкции обозначается значком & и читается как частица и. Это двухместная операция. Например, (х >0)&(x< 1) читается «х больше 0 и х меньше 1». Данная логическая формула примет значение истина, если х
(0,1), and false otherwise. Therefore, the result of a conjunction is true if both operands are true. The sign for the disjunction operation v is read as a particle or. For example, (x = 0) v (x = 1) reads “x equals 0 or x equals 1.” The formula evaluates to true if x is a binary digit (0 or 1). Therefore, a disjunction results in true if at least one operand is true. In Pascal, logical values ​​are denoted by the auxiliary words false and true, and the logical type identifier is boolean.

You have already encountered elements of mathematical logic in the basic school computer science course, studying how to write queries to a database and conditional functions IF in spreadsheets, basics of algorithmization and programming. Let's review the basic concepts of logic in order to further deepen your knowledge of using it for programming.

The basic concepts of logic include: statement, logical value, logical operations, logical expressions and formulas.

Statement (judgment) is a declarative sentence in which something is affirmed or denied. Any statement can be said to be true or false.

For example, the statement "It's raining outside" will be true or false depending on the weather conditions in this moment. The truth of the statement “The value of A is greater than B,” written in the form of an inequality: A > B, will depend on the values ​​of the variables A and B.

Logical values- concepts expressed by words: TRUE, FALSE (true, false). Hence, the truth of statements is expressed through logical quantities.

Logical constant: TRUE or FALSE.

Boolean variable: a symbolically designated logical value. Consequently, if it is known that A, B, X, Y, etc. are variable logical quantities, then it means that they can only take the values ​​TRUE or FALSE.

Boolean expression- simple or complex statement. A complex statement is constructed from simple ones using logical operations (connections).

Logical operations

Conjunction (logical multiplication). In Russian, it is expressed by the conjunction I. In mathematical logic, the signs & or ∧ are used. Conjunction is a two-place operation; written in the form: A & B. The value of such an expression will be FALSE if the value of at least one of the operands is false.

Disjunction (logical addition). In Russian, this connective corresponds to the conjunction OR. In mathematical logic it is denoted by the sign v. Disjunction is a two-place operation; is written in the form: A v B. The value of such an expression will be TRUE if the value of at least one of the operands is true.

Negation. In Russian, this connective corresponds to the particle NOT (in some statements the phrase “it is not true that...” is used). Negation is a unary (one-place) operation; written in the form: ¬ A or Ā.

The rules for performing the considered logical operations are reflected in the following table, which is called the truth table of logical operations (here I means “true”, L means “false”):

Logical formula- a formula containing only logical quantities and signs of logical operations. The result of evaluating a Boolean formula is TRUE or FALSE.

The sequence of operations in logical formulas is determined by the precedence of operations. In descending order of precedence, logical operations are arranged as follows: negation, conjunction, disjunction . In addition, the order of operations is affected by parentheses that can be used in Boolean formulas.

For example: (A & B) v (¬ A & B) v (¬ A & ¬ B).

Example. Calculate the value of a logical formula:

¬ X & Y v X & Z,

if boolean variables have the following values: X= FALSE, Y= TRUE, Z= TRUE.

Solution. Let us mark with numbers above the order of operations in the formula:

Using the truth table, we calculate the formula step by step:

1) FALSE = TRUE; 2) TRUE & TRUE = TRUE; 3) FALSE & TRUE = FALSE; 4) TRUE v FALSE = TRUE. Answer: TRUE.

Logical functions on the range of numerical values

The algebra of numbers intersects with the algebra of logic in cases where it is necessary to check whether the values ​​of algebraic expressions belong to a certain set. For example, the belonging of the value of a numerical variable X to the set of positive numbers is expressed through statement: "X is greater than zero." Symbolically, this is written as follows: X > 0. In algebra, such an expression is called an inequality. In logic - a relation.

The relation X > 0 can be true or false. If X is positive, then it is true; if X is negative, then it is false. IN general view the relation has the following structure:

< выражение 1 > < знак отношения > < выражение 2 >

Here expressions 1 and 2 are some mathematical expressions that take numeric values. In a particular case, an expression can represent one constant or one variable. Relationship signs can be as follows:

So, a relation is a simple statement, and therefore a logical value. It can be either constant: 5 > 0 - always TRUE, 3 * 6: 2 - always FALSE; and the variable: a< b, х + 1 = с - d. Если в отношение входят переменные числовые величины, то и значение отношения будет логической переменной.

The ratio can be thought of as a logical function of the numeric arguments. For example: F(x) = (x > 0) or P(x, y) = = (x< у). Аргументы определены на бесконечном множестве действительных чисел, а значения функции - на множестве, состоящем из двух логических величин: ИСТИНА, ЛОЖЬ.

Logical functions of numeric arguments are also called predicate. In algorithms, predicates play the role of conditions by which branches and cycles are built. Predicates can be either simple logical functions that do not contain logical operations, or complex ones that contain logical operations.

Example 1. Write a predicate (logical function) from two real arguments X and Y, which will take the value TRUE if a point on the coordinate plane with coordinates X and Y lies inside the unit circle centered at the origin (Fig. 3.12).

From geometric considerations it is clear that for all points lying inside the unit circle, the value of the following logical function will be true:

F(X, Y) = (X 2 + Y 2< 1).

For coordinate values ​​of points lying on the circle and outside it, the value of the function F will be false.

Example 2. Write a predicate that will take the value TRUE if a point on the coordinate plane with coordinates X and Y lies inside a ring with a center at the origin, and radii R1 and R2.

Since the values ​​of R1 and R2 are variable quantities, the desired logical function will have four arguments: X, Y, R1, R2. Two situations are possible:

1) R1 2< X 2 + У 2 < R2 2 и R1 < R2: R1 - внутренний радиус, R2 - внешний радиус;

2) R2 2< X 2 + У 2 < R1 2 и R2 < R1: R2 - внутренний радиус, R1 - внешний радиус.

Combining both of these statements with a disjunction and writing them according to the rules of logical algebra, we obtain the following logical function:

F(X, Y, R1, R2) = (((X 2 + Y 2) > R1 2) & ((X 2 + Y 2)< R2 2) & R1 < R2) v (((X 2 + У 2) >R2 2) & ((X 2 + Y 2)< R1 2) & R2 < R1).

Example 3. Write a predicate that will take the value TRUE if a point on the coordinate plane with coordinates X and Y lies inside the figure bounded by the thick lines in Fig. 3.13.

The figure is limited by three boundaries described by the equations:

Y = -X - left border, linear function;

У = 1 - upper limit, constant;

Y = X 2 - right border, parabola.

The region under consideration is the intersection of three half-planes described by the inequalities:

At interior points, all these three relations are simultaneously true. Therefore, the required predicate has the form:

F(X, Y) = (Y > -X) & (Y< 1) & (У >X 2).

Logical expressions in Pascal

It has already been said that Pascal has a logical data type.

Logical constants: true(true), false(lie).

Boolean variables: are described with type Boolean.

Relation operations: compares two operands and determines whether the corresponding relation between them is true or false. Signs of relational operations: = (equal),<>(not equal), > (greater than),< (меньше), >= (greater than or equal to),<= (меньше или равно).

Logical operations: not- denial, and- logical multiplication (conjunction), or- logical addition (disjunction), good- exclusive OR. The truth table for these operations (T - true; F- false):

Boolean expression may consist of logical constants and variables, relations, logical operations. A Boolean expression evaluates to true or false.

For example, the logical formula ¬ X & Y v X & Z in Pascal will be written as the following logical expression:

not X and Y or X and Z,

Where X, Y, Z- type variables Boolean.

Logical operations are arranged in the following order in descending order of precedence (priority): 1) not, 2) and, 3) or, xor. Relational operations have the lowest priority. Therefore, if the operands of a logical operation are relations, they should be enclosed in parentheses. For example, the following logical expression corresponds to the mathematical inequality 1 ≤ X ≤ 50:

(1 <= Х) and(X<= 50)

Logic function odd(x) takes on the value true, if the value of the integer argument X is odd, otherwise - false.

To correctly write a complex logical expression (predicate), you need to take into account the relative priorities of arithmetic, logical and relational operations, since all of them can be present in a logical expression. In descending order of priority, operations are arranged in the following order.

1. Arithmetic operations: - (minus unary) *, / +, - 2. Logical operations: not and or, xor 3. Relational operations: =,<>, >, <, >=, <=

Notice again that in the Boolean expression corresponding to the predicate in Example 3:

(Y > -X) and(Y< 1) and(Y > X * X),

Relational operations are enclosed in parentheses because they are younger than logical operations and must be executed earlier.


Questions and tasks

1. What type of quantity is obtained when calculating the relationship (inequality) between numbers?

2. What is a predicate? Give examples.

3. Write in the language of logical algebra logical functions that will take the value TRUE if the following statements are true, and FALSE otherwise:

A) all numbers X, Y, Z are equal to each other; b) from numbers X, Y, Z only two are equal; c) each of the numbers X, Y, Z positively; d) only one of the numbers X, Y, Z positively; e) meanings of numbers X, Y, Z sorted in ascending order.

4. Write all the formulas obtained when solving the previous problem in the form of logical expressions in Pascal.

5. Construct a truth table for a logical formula:

¬X & Y v X & Z.

Explanation: in the truth table the values ​​of the formula must be calculated for all variants of the values ​​of logical variables: X, Y, Z. Therefore the table will contain 2 3 = 8 rows and 4 columns: values X, Y, Z and the result. You can add additional columns to the table that contain the results of intermediate operations.

6. Calculate the values ​​of the following logical expressions written in Pascal:

Explanations: odd(x)- the logical function for determining the parity of the argument is equal to true, if x is odd, and is equal to false, if x is even; trunc(x)- an integer function of a real argument that returns the nearest integer not exceeding x in absolute value.

Branch programming




Description of the presentation by individual slides:

1 slide

Slide description:

Logical values, operations, expressions. (10th grade) Completed by: computer science teacher MBOU Salganskaya secondary school-Glukhova T.I.

2 slide

Slide description:

The basic concepts of logic include: Statement Logical value Logical operations Logical expressions Formulas

3 slide

Slide description:

A statement (judgment) is a declarative sentence in which something is affirmed or denied. Any statement can be said to be true or false. For example: "It's raining outside" will be true or false depending on the weather conditions at the moment. The truth of the statement “The value is greater than ”, written in the form of inequality: >, will depend on the values ​​of the variables and.

4 slide

Slide description:

Which of the sentences are statements? Determine their truth. How long is this tape? Listen to the message. Do your morning exercises! Name the information input device. Who is absent? Paris is the capital of England. The number 11 is prime. 4 + 5 = 10. You can’t even pull a fish out of a pond without difficulty. Add the numbers 2 and 5. Some bears live in the north. All bears are brown. What is the distance from Moscow to Leningrad?

5 slide

Slide description:

Logical quantities are concepts expressed by words: TRUE, FALSE (true, false). Consequently, the truth of a statement is expressed through logical quantities. Boolean variable: A symbolically designated logical value. For example: if it is known that A, B, X, Y, etc. are variable logical values, then it means they can only take the value TRUE or FALSE. A logical expression is a simple or complex statement. A complex statement is built on simple ones using logical operations (connections)

6 slide

Slide description:

Logical operations Conjunction (logical multiplication) A binary operation, written as A & B. The value of such an expression will be FALSE if the value of at least one operand is false. Disjunction (logical addition) A binary operation, written in the form A V B. The value of such an expression will be TRUE if the value of at least one operand is true. Negation is a unary (one-place) operation. It is written as ¬ A or Ā.

7 slide

8 slide

Slide description:

A logical formula is a formula containing only logical quantities and signs of logical operations. The result of calculating a logical formula is TRUE or FALSE. The sequence of operations in logical formulas is determined by the precedence of the operations. In descending order of precedence, logical operations are arranged as follows: negation, conjunction, disjunction. In addition, the order of operations is affected by parentheses that can be used in Boolean formulas. For example: (A&B)v(Ā&B)v(Ā&B)

Slide 9

Slide description:

Example 1: Calculate the value of a logical formula ¬ X & Y v X & Z If the logical variables have the following values: X=FALSE,Y=TRUE, Z=TRUE. Solution: Let us mark with numbers above the order of operations in the formula: Using the truth table, we calculate the formula step by step: ¬ FALSE = TRUE; TRUE & TRUE = TRUE; FALSE & TRUE = FALSE; TRUE v FALSE = TRUE. ¬ X & Y v X & Z 1 2 3 4

10 slide

Slide description:

Example 2 Determine the value of the logical expression: not (X > Z) and not (X = Y), if: 1) X = 3, Y = 5, Z = 2; 2) X = 0, Y = 1, Z = 19; 3) X = 5, Y = 0, Z = -8; 4) X = 9,Y = -9, Z = 9.

11 slide

Slide description:

Logical functions on the domain of numerical values ​​The algebra of numbers intersects with the algebra of logic in cases where it is necessary to check whether the values ​​of algebraic expressions belong to a certain set. For example, the belonging of the value of a numerical variable X to a set of positive numbers is expressed through the statement: “X is greater than zero.” Symbolically, this is written as follows: X > 0. In algebra, such an expression is called an inequality, and in logic, a relation. The relation X>0 can be true or false. If X is positive, then it is true; if X is negative, then it is false. In general, the relationship has the following structure:<выражение 1> <знак отношения> <выражение2>Relationship signs: = ;<>; >; <; >= ; <=.

12 slide

Slide description:

A relation is a simple statement, and therefore a logical value. It can be either constant: 5>0 – always TRUE, 3≠6:2 – always FALSE; and the variable:a 0) or P(x,y)=(x

Slide 13

Slide description:

Example: Write a predicate (logical function) from two real arguments X and Y, which will take the value TRUE if a point on the coordinate plane with coordinates X and Y lies inside the unit circle centered at the origin. Solution: From geometric considerations it is clear that for all points lying inside the unit circle, the value of the following logical function will be true: F(X,Y)=(X2 +Y2<1) Для значений координат точек, лежащих на окружности и вне её, значение функции Y будет ложным. 1 1 -1 0 Y X

Slide 14

Slide description:

Logical expressions in Pascal Logical constants: true (true), false (false). Boolean variables: are declared with type Boolean. Relational operators: compare two operands and determine whether the corresponding relation between them is true or false. Signs of relational operations Logical operations: not – negation; and – logical multiplication (conjunction); or –logical addition (disjunction); xor – OR exception. Truth table for these operations (T- true, F-false) = ;<>; >; <; >= ; <=. A B not A A and B A or B AxorB T T F T T F T F F F T T F T T F T T F F T F F F

A discipline called mathematical logic is directly related to programming. The basis of mathematical logic is the algebra of logic, or propositional calculus. A statement is any statement that can be clearly stated to be true or false. For example, “The Moon is a satellite of the Earth” is true; “5 > 3” is true; “Moscow is the capital of China” is false; "1 = 0" is false. True or false are logical values. The logical meanings of the above statements are clearly defined; in other words, their values ​​are Boolean constants.

Boolean value of inequality x< 0, где х - переменная, является переменной величиной. В зависимости от значения х оно может быть либо истиной, либо ложью. В связи с этим возникает понятие логической переменной.

He created the foundations of the formal apparatus of mathematical logic in the middle of the 19th century. English mathematician George Boole. In his honor, propositional calculus is called Boolean algebra, and logical quantities are called Boolean.

Single statements can be combined into compound logical formulas using logical operations.

There are three basic logical operations: negation, conjunction (logical multiplication) and disjunction (logical addition).

The operation of negation is denoted in mathematical logic by the symbol ¬ and is read as the particle not. This is a one-person operation.

For example, ¬ (x = y) reads “not (x equals y).” The result is true if x is not equal to y, and false if x is equal to y. Negation reverses the value of a logical value.

The conjunction operation is denoted by & and is read as the particle and. This is a two-person operation. For example, (x > 0) & (x< 1) читается «х больше 0 и х меньше 1». Данная логическая формула примет значение истина, если х

(0,1), and false otherwise. Therefore, the result of a conjunction is true if both operands are true. The sign for the disjunction operation v is read as a particle or. For example, (x = 0) v (x = 1) reads “x equals 0 or x equals 1.” The formula evaluates to true if x is a binary digit (0 or 1). Therefore, a disjunction results in true if at least one operand is true.

In Pascal, logical values ​​are denoted by the function words false and true, and the logical type identifier is boolean.

In addition to values ​​(constants and variables) of type boolean, the logical values ​​false and true accept the results of relational operations.

Relational operations (Figure 18) compare two operands and determine whether the corresponding relation between them is true or false.


Examples of recording relationships: x<у; a+b>=c/d; abs(m-n)<=l. Примеры вычисления значений отношений:

Logical operations are performed on Boolean operands. There are four logical operations: Not - negation; And - logical multiplication (conjunction); Or - logical addition (disjunction). In addition to these three mandatory operations, Turbo Pascal has another operation - exclusive OR. Its sign is the service word Hor. This is a two-place operation that results in true if both operands have different Boolean values.

The operations are listed in descending order of priority. The results of logical operations for various operand values ​​are given in table. 3.5.

Table 3.5


Relational operations have the lowest priority. Therefore, if the operands of a logical operation are relations, they should be enclosed in parentheses. For example, the following logical expression corresponds to the mathematical inequality 1 ≤ x ≤ 50:

(1<=X) And (X<=50)

A logical expression is a logical formula written in a programming language. A logical expression consists of logical operands connected by logical operators and parentheses. The result of evaluating a logical expression is a Boolean value (false or true). Logical operands can be logical constants, variables, functions, and relational operations. A single Boolean operand is the simplest form of a Boolean expression.

Examples of logical expressions (here d, b, c are logical variables; x, y are real variables; k is an integer variable):

If d=true; b=false; c=true; x=3.0; y=0.5; k=5, then the calculation results will be as follows:

The example uses the logical function odd(k). This is a function of the integer argument k, which evaluates to true if k is odd, and false if k is even.

The logical assignment operator has the structure shown in Fig. 19.


Examples of logical assignment operators:

2) b:=(x>y) and (k<>0);

3) c:=d or b and not (odd(k) and d).

Programming Branches in Pascal

Main topics of the paragraph:

♦ branch operator in Pascal;
♦ programming of complete and incomplete branching;
♦ programming nested branches;
♦ logical operations;
♦ complex logical expressions.

Branch operator in Pascal

Pascal has a branch operator. Another name for it is a conditional operator. The format of a complete branch operator is as follows:

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

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

Here if is “if”, then is “that”, else is “otherwise”.

Programming full and incomplete branching

Compare the entry for the BID1 algorithm from the previous paragraph with the corresponding program.

Very similar to translation from Russian into English. Please note the following difference: the program does not have a special function word to indicate the end of a branch. Here, the end of a branch statement is indicated by a semicolon. (Of course, leaving an empty line in the program is not at all necessary. This is done here only for the sake of clarity.)

A simple form of a Boolean expression is the relational operator. As in AY, all types of relations are allowed in Pascal (their signs are indicated below):

< (меньше); >= (greater than or equal to);
> (more); = (equal);
<= (меньше или равно); <>(not equal).

Now let’s program the BID2 algorithm in Pascal, which uses incomplete branching.

Again everything is very similar. The else branch may not be present in a branch statement.

Programming Nested Branches

Let's write a program in Pascal to determine the largest of three numbers, the block diagram is shown in Fig. 6.6. The structure of this algorithm is nested branches. The algorithm in AY (BIT2) is given in the previous paragraph.

Please note that there is no semicolon before else. The entire branching part of the algorithm structure ends at the semicolon after the D:=C operator.

Let's create a program for ordering the values ​​of two variables.

This example illustrates the following Pascal rule: if there are several consecutive operators on any branch of the branch operator, then they must be written between the service words begin and end. This type of design:

begin<последовательность операторов>end

is called a compound operator. Therefore, in the general form of branching described above<оператор1>And<оператор2>can be simple (single) or compound statements.

Logical operations

Finally, let's create another, third version of the program for determining the largest number out of three.

It is not difficult to understand the meaning of this program. Three consecutive incomplete branches are used here. And branch conditions are complex logical expressions that include the logical operation and (AND). You've encountered logical operations while working with databases and spreadsheets.

Recall that the and operation is called logical multiplication or conjunction. Its result is true if both operands are true. Obviously, if A>B and A>C, then A has the greatest value, etc. All three basic logical operations are present in Pascal:

and - AND (conjunction),
or - OR (disjunction),
not - NOT (negation).

Complex logical expressions

Note that relations connected by logical operations are enclosed in parentheses. This is how you should always do it! For example, you need to determine whether among the numbers A, B, C there is at least one negative one. The following branch operator solves this problem:

if (A<0) or (B<0) or (C<0)
then write("YES") else write("NO");

An expression true for a negative number can also be written like this:

Briefly about the main thing

Pascal's branch operator (conditional operator) has the form:

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

Branches of a conditional statement can contain simple or compound statements. A compound statement is a sequence of statements enclosed between the function words begin and end.

Complex logical expressions use logical operations: and, or, not.

Questions and tasks

1. How to program complete and incomplete branching in Pascal?
2. What is a compound operator? When is a compound operator used in a branch operator?
3. Run all the programs given in this paragraph on your computer.
4. Make at least three versions of a program for determining the smallest of three given numbers.
5. Create a program for sorting in ascending order of values ​​in three variables: A, B, C.
6. Create a program for calculating the roots of a quadratic equation using the given values ​​of its coefficients.

Edited Date: Monday, 30 December 2019
Did you like the article? Share it