Boolean values \u200b\u200bin pascal are. Pascal operations. Pascal. Conditional if statement. Format and principle of operation

Laboratory work No. 3

Theme:Boolean type.

There are two logical constants in Pascal: TRUE and FALSE. A boolean variable can take any of these values \u200b\u200band is of type boolean. Boolean data is widely used to validate certain conditions and compare values. The result can 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)

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

When evaluating the values \u200b\u200bof Boolean expressions, consider the order in which the Boolean operations are performed. The NOT operation has the highest priority, followed by the AND operation, and then the OR operation. Comparison operations have the lowest precedence.

Boolean variables are described in the variable declaration section using the standard BOOLEAN identifier.

Example: a, R1, f: boolean ;.

There are functions in Pascal that take the boolean type:

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

2. EOLN - value is true if end of line text file.

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

Sample program:

var a, b, c: integer;

writeln (‘enter three integers’);

write ('s \u003d', s);

As a result of executing the program, 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, i.e. TRUE or FALSE appears on the screen.

Tasks 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 if 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 this number.

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

    Determine if there are identical digits of a given three-digit number.

    Three arbitrary numbers are given. Determine if you can build a triangle with these side lengths.

    Build a logical equation using all logical operations with displaying a logical variable.

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

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

Tasks 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 if 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 this number.

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

    Determine if there are identical digits of a given three-digit number.

    Three arbitrary numbers are given. Determine if you can build a triangle with these side lengths.

    Build a logical equation using all logical operations with displaying a logical variable.

    Determine if 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 if a circle can be inscribed in it.

Software - Pascal Pascal operations

Pascal operations

Operations specify actions on operands. In the Pascal language, there are binary and unary operations. Unary operations contain 1 operand, preceded by an operation sign. Binary operations have 2 operands, between which the sign or symbol of the operation is placed. By the nature of the actions pascal operations can be divided into 7 groups:

  • arithmetic;
  • relationship;
  • brain teaser;
  • string;
  • bit, shift;
  • operations on sets;
  • operations of taking the address.

Arithmetic operations. In Pascal, there is one unary operation called assignment of a minus sign and a second assignment of a plus sign. Binary are:

  • addition (+);
  • subtraction (-);
  • multiplication (*);
  • real division (/);
  • integer division (div);
  • remainder of integer division (mod).

In Pascal, there are three division operations, division (/) is a fractional number, div is only an integer, and mod is the remainder of an integer division. Examples:

Only operands of numeric types can take part in arithmetic operations. Their result will also be a number. The number can be whole or real.

Relationship operations. These include all binary operations:

  • more;
  • less;
  • more or equal;
  • less or equal
  • equally
  • not equal.

The result of relations operations can only be a Boolean variable; it can take either the value True or False. Operands in a relational operation can be numeric types or types that are reducible to numeric types. Numeric types:

  • symbolic - in relation operations, character codes are compared in accordance with the code table;
  • boolean - the values \u200b\u200bTrue and False are used, taking values \u200b\u200b1 - true and 0 - false, respectively;
  • string - a complex type consisting of a character type. Therefore, when using strings, a comparison is made between consecutive characters in two strings.

For instance:

5.6\u003e 7 - False;

'P'< ‘Б’ — False;

‘Petrov’\u003e ‘Ivanov’ - True;

‘Ivanov’< ‘Иван’ — False.

Boolean operations will result in Boolean values \u200b\u200bTrue or False.

Unary: NOT - negation.

Binary: AND - multiplication (and); OR - addition (or); XOR - modulo 2 addition (exclusive OR).

Operands of a logical expression can only be operations of a logical type.

String operations. Concatenation (concatenation) is a binary operation. Only variables of string type can be operands. The result is a string, and the action of the operation is to concatenate two strings into one:

A: \u003d ‘Ivanov’

B: \u003d ‘Alexander’

Result: Ivanov Alexander.

The sequence of operations in Pascal is determined by 3 factors:

  • priority of operations;
  • order of arrangement of operations;
  • use of brackets.

Priority levels of operations performed:

  • first priority operations are performed first;
  • the lowest priority operations are executed last;
  • operations with equal priority are performed from left to right in the order they were written.

At the same time, the compiler can sometimes reorder the operands of the same priority. To change the priority (increase it), use parentheses. The parenthesized expression is first evaluated and then evaluated outside the parentheses.

Description: var n: boolean;

Boolean data can only have two values: true and false. For values \u200b\u200bof a boolean type, comparison operations, and true> false.Also applies 4 logical operations:

and logical multiplication

or logical addition

xor exclusive "or"

not negation

The rules for performing logical operations are defined using the following truth tables:

X and Y

X xor Y


Example 1:

not (5\u003e 2) \u003d false

(5\u003e 2) and (3<10) = true

(8<>9) or (4\u003e 5) \u003d true

not (5 \u003d 2) xor (3\u003e 2) \u003d false

Example 2:

When comparing BOOLEAN data, the internal Turbo Pascal convention is taken into account, according to which FALSE is a zero byte, and TRUE is a byte with a one in the least significant bit. Note that the ORD function converts not only symbols, but also logical values \u200b\u200bto an integer, therefore

2.5 Limited types

On the basis of standard types, you can build your own types, limiting the range of possible values: 1..10, -100..10, 'a' .. 'z', etc.

Example:

b: 'a' .. 'z';

b: \u003d 0; (error: type mismatch - an integer is assigned to a character type variable)

a: \u003d 0; (error: out of range 2..5)

2.6 Enumerated types

They are formed by explicitly listing all possible values \u200b\u200bspecified by names. For example, for a traffic light control program, the following type can be defined:

var svet: (red, yellow, green);

oper: (plus, minus);

The boolean type is a special case of the enumerated type.

2.7 Description of types

New data types in Pascal are defined by means of descriptions starting with the word TYPE. The description consists of the type name and the type value, between which the "\u003d" sign is placed.

Example:

abc \u003d 'A' .. 'z';

2.8 Type conversion

As already mentioned, the type of a variable allows not only to set the length of its internal representation, but also to control the actions that are performed on it in the program. Control over the use of variables even at the stage of program compilation is an important advantage of Turbo Pascal over other programming languages \u200b\u200bthat allow automatic type conversion. In Turbo Pascal, implicit (automatic) type conversions are almost impossible. The only exception is made for constants and variables of type INTEGER (integers), which are allowed to be used in expressions of type REAL (real). If, for example, the variables X and Y are described as follows:

var x: integer;

then the operator

will be syntactically correct: although there is an integer expression to the right of the assignment sign, and a real variable to the left, the compiler will make the necessary conversions automatically. At the same time, the operator

will be incorrect, since the automatic conversion of the REAL type (the 2.0 constant contains a decimal point and therefore is of the REAL type) to INTEGER is prohibited in Turbo Pascal.

Thus, variables can only be assigned values \u200b\u200bof their own type; the only exception: a variable of a real type, and the value of an integer (in this case, the integer will be converted to a real with a fractional part equal to 0).

Of course, the ban on automatic type conversion does not mean that Turbo Pascal does not have data conversion tools. They are, of course, there, but they must be used explicitly. To transform data in the language, there are built-in functions that receive a value of one type as a parameter, and return the result as a value of another type. In particular, there are even two built-in functions of this kind for converting REAL to INTEGER: ROUND rounds REAL to the nearest integer, and TRUNC truncates REAL by discarding the fractional part (see section 1.5).

For example, the operator

but correct

x: \u003d round (y / x);

(see variable declarations above).

For example, the ORD function is used to convert data of the CHAR (character) type to an integer; the CHR function performs the reverse conversion from INTEGER to CHAR.

The presence of two division operations is another manifestation of the fundamental principle of Turbo Pascal: the programmer must explicitly confirm to the compiler that he is prepared for the possible consequences of type conversion. If, for example, the expression 1/2 is used in the Fortran language, then the result of this expression will depend on the variable of which type it will be assigned: if N is a variable of an integer type, and X is a real one, then in a Fortran program the assignments

will give the values \u200b\u200b0 for N and 0.5 for X. Turbo Pascal does not have this ambiguity: the expression 1/2 is always 0.5 and therefore the operator

is simply unacceptable. At the same time, operators allowed in Turbo Pascal are:

And finally, about relation operations and logical operations.

The following relations (comparison) operations are defined on data of type REAL, INTEGER, CHAR, STRING:

<> - not equal;

< - меньше;

\u003e - more;

<= - меньше или равно,

\u003e \u003d - greater than or equal.

Operands of the same type must be used in comparison operations. An exception is made again in relation to REAL and INTEGER, which can be compared with each other. The result of applying the relational operation to any operands is of type BOOLEAN.

The lesson discusses the conditional operator in Pascal ( if). Explains how to use multiple conditions in one construct ( AND and OR). Examples of working with the operator are considered

We remind you that this site does not claim to be a complete presentation of information on the topic. The purpose of the portal is to provide an opportunity to assimilate the material on the basis of ready-made solved examples on the topic "Pascal Programming Language" with practical tasks to consolidate the material. The Pascal assignments presented on the site are lined up sequentially as their complexity increases. The site site can be used by teachers and teachers as an auxiliary visual aid.

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

A block diagram of a conditional operator:

A conditional operator 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 the task in such a way that the sequence of execution of the operators changes depending on any logical condition. A logical condition can take one of two values: either true (true) or false (false), respectively, it can be either true or false.

Compound operator

If under a true condition it is necessary to execute several operators, then according to the rules of the Pascal language, they must be enclosed in a block, starting with the service word begin and ending with the service word end. Such a block is usually called operator brackets, and this construction - compound operator:

Operator brackets and compound operator in Pascal:

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

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

IF THEN ELSE
IF A TO ELSE


In a condition (in a logical expression), relational operators are used.
Consider a list of Pascal relation operators:

  • more\u003e
  • less
  • greater than or equal in Pascal\u003e \u003d
  • less than or equal in Pascal
  • comparison in Pascal \u003d
  • 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 along one of the two branches

Show solution:

var x, y: real; begin writeln ("enter x"); read (x); if x\u003e 0 then y: \u003d ln (x) else y: \u003d exp (x); writeln ("y \u003d", y: 6: 2) (the total number will occupy 6 positions, and there will be 2 decimal places in it) end.

Note how in this example y is output. When printing type variables in pascal, you can use the so-called formatted output, or notation with two colons:
y: 6: 2
- the digit after the first colon (6) indicates how many characters the number will take when displayed on the screen
- the digit after the second colon (2) indicates how many digits after the decimal point of the real number will be displayed

Thus, the use of such a notation in pascal practically allows rounding to hundredths, thousandths, etc.

Problem 0. Calculate the value of the variable y along one of the two branches:

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

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

Boolean operations in Pascal (in boolean terms)

When it is necessary to use a double condition in Pascal, then logical operations are needed.

  • Logical operation AND (And), put 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".
  • Between two conditions, the sign OR (OR) indicates 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 - the sign of a logical operation, which has the meaning of "strict disjunction" and indicates that it is necessary that one of the two conditions is fulfilled (true), and the other is not fulfilled (false).
  • Logical operation NOT before a logical expression or variable has the meaning of "negation" or "inversion" and indicates that if the given variable or expression is true, then their negation is false and vice versa.

Important: Each of the simple conditions must be enclosed in parentheses.

Example: Consider examples of logical operations in logical expressions in Pascal

1 2 3 4 5 6 7 8 var n: integer; begin n: \u003d 6; if (n\u003e 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 ("truth"); end.

var n: integer; begin n: \u003d 6; if (n\u003e 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 ("truth"); end.

Example:The company recruits employees from 25 to 40 years inclusive. Enter the person's age and determine if he is suitable for the given company (output the answer "suitable" or "not suitable").
Feature: it is necessary to check whether two conditions are fulfilled simultaneously.

Turbo Pascal data type concept

For computer processing, data are presented in the form of quantities and their aggregates. The concept of magnitude is associated with the following important characteristicas her type.

The type defines:

Possible values \u200b\u200bof 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 \u200b\u200bbelonging to this type.

In Pascal, the type of a value is predefined. All variables used in the program must be declared in the description section with an indication of their type. A mandatory type declaration leads to redundancy in the text of programs, but such redundancy is an important auxiliary tool for developing programs and is considered a necessary property of modern algorithmic languages high level.

The type hierarchy in Pascal is as follows:

Simple

o Ordinal

§ Brain teaser

§ Symbolic

§ Enumerable

§ 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 understood as any statement in relation to which it is possible to say unambiguously whether it is true or false. For example, "The moon is a satellite of the Earth" is true; "5\u003e 3" is true; “Moscow is the capital of China” is false; "1 \u003d 0" is false. True or false are logical values. The logical meanings of the above statements are uniquely defined; in other words, their values \u200b\u200bare logical 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, the propositional calculus is called Boolean algebra, and logical values \u200b\u200bare called Boolean.

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

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

The negation operation is denoted in mathematical logic by the icon and is read as NOT. This is a single operation.

For example, (x \u003d 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 Boolean value.

The conjunction operation is denoted by & and reads AND. This is a two-place operation. For example, (x\u003e 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, boolean values \u200b\u200bare denoted by the service words True and False, and the boolean data type is called BOOLEAN.

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

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

Boolean data takes up one byte of memory. In this case, false corresponds to a zero byte value, and true 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 into the corresponding memory field. In these operations, operands of the boolean type are considered as a whole - regardless of the bit composition of their internal representation. Also, 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 indicated by a name in the CONST section, for example:

Boolean variable can also take two values \u200b\u200bTRUE and FALSE. Boolean variables must be described by a sentence:

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

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

It should be noted that in the section describing variables it is necessary to define the type of variables used in the program. For instance,

Var P, Q, R: Integer;

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

L1: \u003d true; L2: \u003d false; L3: \u003d L1;

Boolean values \u200b\u200bcan be assigned, displayed, but not entered by the read procedure.

Boolean Variables Example