Logical expressions (conditions) in the Pascal language they are used in if statements and when organizing repetitions, namely in while loops and repeat–until.

Examples of logical expressions:

1 . a > 2*b

2 . sin(sqr(a))<= exp(cos(b))–2.3

3 . (a<= 3) and (b >a/2)

Logical expressions are based on relation operations

(<, >, <= , >=, =, <>)

And logical operations

and(logical and),

or(logical or),

not(logical negation),

xor(exclusive or).

The result execution of a Boolean expression is a Boolean value true(true) or false(lie). In complex logical expressions, arithmetic operations are performed first, logical operations second, and relational operations last.

24 Pascal. Conditional if statement. Format and principle of operation.

The structure of the if conditional statement looks like this:

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

where if, then, else are reserved words (if, then, otherwise);

<условие> – logical expression;

<оператор1>And<оператор2>– any Pascal language operators (simple or compound).

Example: if sin(a)>b then y:= a

The if statement works like this:

<условие>(true (true) or false (false)).

If the value<условие>– true (true), then executed<оператор1>, A<оператор2>ignored.

If the value<условие>– false (false), then executed<оператор2>, A<оператор1>ignored.

Shorthand if statement

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

Examples: if a< 2*b then y: = a/2 ;

if a< 2*b then begin

In example 1 operator y:=a/2; is a simple Pascal operator.

In example 2, the operator begin y:=2*a; writeln(y)end; is compound operator Pascal language.

Compound operator is a group of statements enclosed in operator brackets begin end:

begin<операторы>;

Used when it can be done only one operator according to the rules of Pascal syntax, and the task assumes the execution of a group of operators.

The shorthand if statement is executed as follows.

The value of a logical expression is calculated<условие>.

If the result is true, control is transferred to<оператор>.

If the result of the condition is false,<оператор>is ignored, and control of program execution is transferred to the next statement in the program.

25 Pascal. The case…of selection operator. Format and principle of operation. Case selection operator

If the conditional statement if allows you to implement one of two possible continuations of the program, then the case statement provides the opportunity to choose one of several continuations of the program.

This operator has the structure:

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

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

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

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

else<оператор>

Here<выражение-селектор>– an expression or, in a particular case, a variable of any scalar type other than real (usually a variable of type byte, integer, boolean or char);

<список1, список2, ... списокN>– lists of constants whose values ​​the selector expression can take. Each list can be a constant, a range of constants, or several constants (ranges) separated by a comma.

The else clause may not be present in the case statement.

The case statement is executed as follows.

    The value of the selector expression is analyzed.

    If the value of the selector expression does not match any of the constants in the constant lists, control is transferred to the statement after the else word, and if there is no else word, to the statement following the case statement.

Hello, dear readers of our site! Today, we will talk about logical type variables Boolean to Pascal, logical operations and solve five problems.

Why do you need logic in Pascal? You, I hope, have already learned to write the simplest linear programs, and now you are probably wondering how to write nonlinear program? In order for a program to be nonlinear in Pascal, as in other programming languages, they use logical expressions that take values true or false. That is, true or false is put in place of any relation in Pascal. For example,

Var A: integer; begin A:= 5; write(A > 0); (True will be printed.) end.

List of relational operators:

  • more: >
  • less:<
  • greater than or equal to: >=
  • less than or equal to:<=
  • equals: =
  • not equal:<>

In order to record the result of a logical expression, we need a special variable. This variable will be of type boolean and can take two values ​​- true or false. You already understand how to create simple conditions, but how to create complex conditions? For this, special logical operations are used: and, or, not And xor. Let's look at each operation separately and create truth tables. Let's take 1 to be true, and 0 to be false.

And, or conjunction.


Logical multiplication is true only when both simple statements are true.

Or, or disjunction.

True if at least one simple statement is true.

Xor, or strict disjunction.


True if exactly one of two simple statements is true.

Not, or inversion.


If a statement is true, then its negation is a lie and vice versa.

Boolean tasks.

Let's consolidate our knowledge by solving a couple of problems.

. Given an integer A. Check the truth of the statement: “The number A is positive.”

ProgramBoolean1; var a: integer; begin write("Enter number A: "); read(a); writeln("The number A is positive - ", a > 0); (A simple statement.) end.

. Given an integer number A. Check the truth of the statement: “The number A is odd.”

In order to find out whether a given number is odd, Pascal provides a special function Odd, which returns true, if the number is odd and false, if the number is even.

ProgramBoolean2; var a: integer; b: boolean; begin write("Enter number A: "); read(a); b:=Odd(a); writeln("The number A is odd - ", b); (You can do without b) end.

. Given an integer number A. Check the truth of the statement: “The number A is even.”

In order to find out whether a number is odd, we use a function we already know, then invert the result.

ProgramBoolean3; var a: integer; b: boolean; begin write("Enter number A: "); ( 6 ) read(a); b:=Odd(a); ( False ) writeln("The number A is even - ", not b); (True) end.

. Given three integers: A, B, C. Check the truth of the statement: “The number B is between the numbers A and C.”

Program Boolean7; var a, b, c: integer; b1, b2: boolean; begin write("Enter number A, B, C: "); read(a, b, c); b1:= (B > A) and (B< C); b2:= (B >C) and (B)< A); { Надо учитывать оба варианта } writeln("Число B находится между числами A и C - ", b1 or b2); end.

. Given two integers: A, B. Check the truth of the statement: “Exactly one of the numbers A and B is odd.”

We use xor.

ProgramBoolean10; var a, b: integer; c:boolean; begin write("Enter number A, B: "); read(a, b); c:= (Odd(a)) xor (Odd(b)); ( How many parentheses 🙂 ) writeln("Exactly one of the numbers A and B is odd - ", c); end.

. A four-digit number is given. Check the truth of the statement: “This number is read the same from left to right and from right to left.”

We use the knowledge gained in the lesson.

So, this task checks whether the entered four-digit number is a palindrome. Surely, the most famous palindrome is Malvina’s phrase: “And the rose fell on Azor’s paw.” (Try reading this sentence from right to left)

ProgramBoolean23; var a, b, c, d, e, f: integer; b1, b2: boolean; begin write("Enter a four-digit number: "); read(e); a:= e div 1000; b:= e mod 1000 div 100; c:= e mod 100 div 10; d:= e mod 100 mod 10; f:= d * 1000 + c * 100 + b * 10 + a; writeln("This number is a palindrome - ", f = e); end.

That's all for today! Don’t forget to visit our website periodically, subscribe and click on the buttons!

This lesson introduces the logical type Boolean in Pascal. The algorithm of how to find minimum And maximum number in Pascal


The website provides laboratory assignments on the topic to reinforce theoretical material and gain practical programming skills in Pascal. Brief theoretical information will allow you to obtain the minimum knowledge necessary for this. Solved visual examples and laboratory tasks are presented in order of increasing complexity, which makes it easy to study the material from scratch. Good luck!

We have already learned how to write programs based on linear algorithms in Pascal. And we are even already compiling nonlinear algorithms - with branching - that use , which take the values ​​true or false.

Boolean values:

In the example below, the result of a logical expression is displayed on the screen:

1 2 3 4 5 6 var A: integer ; begin A := 5 ; write(A > 0); (True will be output) end.

var A: integer; begin A:= 5; write(A > 0); (True will be output) end.

To record the result of a logical expression, a special logical variable is used, which in Pascal is of type boolean and can also take one of two values ​​- true or false.

Let's see how the same task works with a boolean variable:

1 2 3 4 5 6 7 8 var A: integer ; b:boolean ; begin A := 5 ; b: = A > 0 ; write(b); (True will be output) end.

var A: integer; b: boolean; begin A:= 5; b:=A > 0; write(b);(True will be printed) end.

Example: Let's look at an example of working with the boolean type in Pascal:

var a:boolean; begin a:=true; if a=true then writeln("true") else writeln("false"); end.

To create complex conditions, special ones are used: and, or, not and xor.

Boolean task 1. A positive integer is given. Check the truth of the statement: “it is even”

Let's look at an example using the logical XOR operation:

Example: Request two integers: X, Y. Check the truth of the statement: “Only one of the numbers X and Y is odd”

programBoolean; var x,y: integer; c:boolean; begin write("Enter X, Y: "); read(x,y); c:= (Odd(x)) xor (Odd(y)); writeln("Only one of the variables X and Y has an odd value - ", c); end.

Let's consider another solution to the problem in Pascal using a logical variable:

Boolean task 2. Given three integers: A, B, C. Check the truth of the statement: “B is between the numbers A and C.”

Let's consider solving a more complex problem with a variable of logical type:

Example: A three-digit number is given. Check the truth of the statement: “All numbers given number are different."

Show solution:

1 2 3 4 5 6 7 8 9 10 11 12 13 const a= 348 ; var d_n, s_n, e_n: integer ; flag:boolean ; begin flag: = false ; s_n: = a div 100 ; d_n: = ((a mod 100 ) div 10 ) ; e_n: = a mod 10 ; if (s_n<>d_n) and (d_n<>e_n) and (e_n<>s_n) then flag: = true ; writeln(flag); end.

const a=348; var d_n, s_n, e_n: integer; flag:boolean; begin flag:=false; s_n:=a div 100; d_n:=((a mod 100)div 10); e_n:=a mod 10; if (s_n<>d_n) and (d_n<>e_n) and (e_n<>s_n) then flag:=true; writeln(flag); end.

Here, each digit is obtained by using the operations of division by an integer and taking the remainder of the division: s_n is the digit of the hundredth digit, d_n is the digit of the tenth digit, e_n is the ones.

Boolean task 3. Given an integer N > 0 . Using the operations of dividing by an integer and taking the remainder of the division, determine whether the number N contains the digit “2”. If there is, then print TRUE, if not, print FALSE.

Boolean task 4. A positive integer is given. Check the truth of the statement: “This number is an odd three-digit number.”

Minimum and maximum number in Pascal

When organizing a search for the minimum or maximum number among a series of numbers, an old “grandmother’s” algorithm always comes to the rescue:

  • Let's imagine the situation that we are frying pies, and we have already fried a whole large pile; Now you need to choose the largest of them, i.e. in our case the maximum.
  • We take the top pie, i.e. the first one, and we say that it is the largest so far and put it aside.
  • Then we take the second one and compare it with the largest one; if this second pie turns out to be larger, we put it in place of the “former largest one” and say that it is now the largest one.
  • Take the next one and repeat the steps. So we carry out this procedure with all the pies.

Sometimes the smallest possible number is assigned as the initial maximum (depending on the context of the problem). And as a minimum, on the contrary, the largest possible number. For example, if you say that you need to find the maximum/minimum among positive numbers less than 1000, then:

max: = 0 ; min: = 1000 ;

The concept of data type in Turbo Pascal

For computer processing, data is presented in the form of quantities and their sets. Associated with the concept of quantity is such an important characteristic as its type.

Type defines:

· possible values ​​of variables, constants, functions, expressions belonging to this type;

· internal form of data presentation in a computer;

· operations and functions that can be performed on values ​​belonging to a given type.

In Pascal, the type of a value is specified in advance. All variables used in the program must be declared in the declaration section indicating their type. The mandatory type description leads to redundancy in the text of programs, but such redundancy is an important auxiliary means of program development and is considered as a necessary property of modern algorithmic languages high level.

The type hierarchy in Pascal is as follows:

· Simple

o Ordinal

§ Brain teaser

§ Character

§ Listable

§ Interval

o Real

Structured

o Arrays

o Sets

· Pointers

Boolean data types

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” - 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, где x – переменная, является переменной величиной. В зависимости от значения x оно может быть либо истиной, либо ложью. В связи с этим возникает понятие логической переменной.

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 negation operation is denoted in mathematical logic by an icon and is read as NOT. This is a one-person operation.

For example, (x = y) reads “not (x equals y).” The result will be 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 AND. It is a two-place operation. For example, (x > 0) & (x< 1) читается «x больше 0 и x меньше 1». Данная логическая формула примет значение истина, если x Є (0,1), и ложь – в противном случае. Следовательно, результат конъюнкции – истина, если истинны оба операнда. Знак операции дизъюнкции V читается как ИЛИ. Например, (x = 0) V (x = 1) читается «x равно 0 или x равно 1». Формула дает истину, если x – двоичная цифра (0 или 1). Следовательно, дизъюнкция дает в результате истину, если хотя бы один операнд - истина.

In Turbo Pascal, logical values ​​are denoted by the service words True and False, and the logical data type is called BOOLEAN.

All implementations Pascal language, including Turbo Pascal, up until version 6.0, contained only one Boolean data type, the elements of which can only take the above two Boolean values. Turbo Pascal version 7.0 added three more logical data types: ByteBool, WordBool and LongBool.

By analogy with integer and character types, divided into physical and logical, it is natural to assume that ByteBool, WordBool and LongBool - physical types, Boolean - logical. But in this case this is not entirely true. All four types are different. For Turbo Pascal, the logical type Boolean is more preferable, since it uses less memory; the remaining types were introduced to ensure compatibility of the developed programs with Windows, in which the value False corresponds to 0, and the value True corresponds to any number other than 0.

Boolean data takes up one byte of memory. In this case, the false value corresponds to a zero byte value, and the true value corresponds to any non-zero byte value. For example: false always in machine representation: 00000000; true might look like this: 00000001 or 00010001 or 10000000.

However, it should be borne in mind that when performing an operation of assigning a variable of a Boolean type to true, the code 00000001 is always written to the corresponding memory field. In these operations, the Boolean type operands are considered as a single whole - regardless of the bit composition of their internal representation. In addition, remember that Boolean results are obtained when comparing data of any type. The Turbo Pascal Boolean constants TRUE and FALSE can be used explicitly or designated by a name in the CONST clause, for example:

A Boolean variable can also take on two values: TRUE and FALSE. Boolean variables must be described by the following statement:

Var<имя_переменной>: boolean; (Variable variable).

For example: var L,A,C:boolean;

Please note that in the variable description section, you must define the type of variables used in the program. For example,

Var P,Q,R: Integer;

In the statements section, the logical type of a variable can be assigned the value of a logical constant, for example:

L1:=true; L2:=false; L3:=L1;

Boolean data type values ​​can be assigned and output, but cannot be entered by the read procedure.

Example of variables with boolean value

Laboratory work No. 3

Subject: Logical type (boolean).

Pascal has two logical constants: TRUE (true) and FALSE (false). A boolean variable can take any of these values ​​and is of type boolean. Logical data is widely used in checking the validity of certain conditions and in comparing quantities. The result may be “true” or “false”. The following operations are allowed on logical data:

Boolean operations:

Operator

Operation

Operand type

Result type

negation

logical AND

logical OR

logical exclusive OR

The results of operations on logical data are summarized in the table:

(A) and (B)

(A) or (B)

From Boolean data, comparison operations and Boolean operations logical expressions are constructed that have boolean values. For example: (c10) or (d

When evaluating the values ​​of Boolean expressions, you must consider the order in which the Boolean operations are performed. The NOT operator has the highest priority, followed by the AND operator, and then the OR operator. Comparison operations have the lowest priority.

Variables of the Boolean type are described in the variable declaration section using the standard identifier BOOLEAN.

Example: a, R1, f: boolean;.

In the Pascal language there are functions that accept the boolean type:

1. ODD(A)- the value is true when A is not an even number.

2. EOLN- true if end of string text file.

3. EOF- true if the end of the text file.

Example program:

var a,b,c:integer;

writeln('enter three integers');

write(‘s=’,s);

As a result of program execution, the variable s will be assigned the value TRUE or FALSE, depending on whether the logical expression was false or true, and the value of the variable s will be displayed on the screen, i.e. TRUE or FALSE will appear on the screen.

Assignments for laboratory work No. 3.

For execution laboratory work It is necessary to write programs that print true or false depending on whether the specified conditions are met or not:

    For arbitrary real numbers a, b and c, determine whether the quadratic equation has at least one real solution.

    Determine whether the sum of the first two digits of a given four-digit number is equal to the sum of its last two digits.

    Determine whether the square of a given three-digit number is equal to the cube of the sum of the digits of that number.

    Determine whether among the first three digits of the fractional part of the given positive real number number 0.

    Determine whether among the digits of a given three-digit number there are identical ones.

    Three arbitrary numbers are given. Determine whether it is possible to construct a triangle with these side lengths.

    Create a logical equation using all logical operations with a logical variable displayed on the screen.

    Determine whether the square of a given number is greater than the square root of another given number.

    The lengths of the sides of a convex quadrilateral are expressed numbers a,b,c,d. Determine whether a circle can be inscribed in it.

Assignments for laboratory work No. 3.

To complete the lab, you need to write programs that print true or false depending on whether the specified conditions are met or not:

    For arbitrary real numbers a, b and c, determine whether the quadratic equation has at least one real solution.

    Determine whether the sum of the first two digits of a given four-digit number is equal to the sum of its last two digits.

    Determine whether the square of a given three-digit number is equal to the cube of the sum of the digits of that number.

    Determine whether among the first three digits of the fractional part of a given positive real number there is a digit 0.

    Determine whether among the digits of a given three-digit number there are identical ones.

    Three arbitrary numbers are given. Determine whether it is possible to construct a triangle with these side lengths.

    Create a logical equation using all logical operations with a logical variable displayed on the screen.

    Determine whether the square of a given number is greater than the square root of another given number.

    The lengths of the sides of a convex quadrilateral are expressed by the numbers a,b,c,d. Determine whether a circle can be inscribed in it.