• Pascal logical operations. Boolean data types. An example of an enumerated type declaration

    Description: varn: boolean;

    Boolean data can only take two values: true (true) and false (false). For values ​​of a boolean type, comparison operations, and true> false.Also apply 4 logical operations:

    and logical multiplication

    or logical addition

    xor exclusive "or"

    not negation

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

    X and Y

    Xxor Y


    Example 1:

    not(5>2) = false

    (5>2) and (3<10) = true

    (8<>9) or (4>5) = true

    not (5=2) xor (3>2) = false

    Example 2:

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

    2.5 Restricted types

    Based on 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:=0; (error: type mismatch - a character type variable is assigned an integer)

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

    2.6 Enumerated types

    Formed by explicit enumeration of all possible values ​​given by names. For example, for a traffic light control program, the following type could be defined:

    var svet: (red, yellow, green);

    opera: (plus, minus);

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

    2.7 Description of types

    New data types in Pascal are defined by declarations beginning with the word TYPE. The description consists of a type name and a type value, between which the "=" sign is placed.

    Example:

    abc='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 at the stage of program compilation is an important advantage of Turbo Pascal over other programming languages ​​that allow automatic type conversion. In Turbo Pascal, implicit (automatic) type conversions are almost impossible. An exception is made only 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 declared 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 do the necessary conversions automatically. At the same time, the operator

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

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

    Of course, the ban on automatic type conversion does not mean that there are no data conversion tools in Turbo Pascal. They, of course, are, but they need to be used explicitly. To convert 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 would be erroneous

    but right

    x:= round(y/x);

    (see variable declarations above).

    For example, the ORD function is designed to convert data of the CHAR (character) type into an integer, while the reverse conversion of INTEGER to CHAR is performed by the CHR function.

    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 ready 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 what type of variable it will be assigned to: if N is a variable of an integer type, and X is of a real type, then in a Fortran program the assignments

    will give the values ​​0 for N and 0.5 for X. There is no such ambiguity in Turbo Pascal: the expression 1/2 always has the value 0.5 and so the operator

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

    And, finally, about relational and logical operations.

    The following relational (comparison) operations are defined over data of REAL, INTEGER, CHAR, STRING types:

    <>- not equal;

    < - меньше;

    > - more;

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

    >= - greater than or equal to.

    Comparison operations must involve operands of the same type. An exception is made again for REAL and INTEGER, which can be compared with each other. The result of applying the relational operator to any operands is of type BOOLEAN.

    Software - Pascal Pascal language operations

    Pascal language operations

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

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

    Arithmetic operations. Pascal has one unary operation called minus sign assignment and a second plus sign assignment. Binaries are:

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

    Pascal has three division operations, the result of the division (/) operation is a number with a fractional part, the result of the div operation is only an integer, and the result of the mod operation 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 integer or real.

    relation operations. These include all binary operations:

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

    The result of relational operations can only be a boolean variable, it can take either the value true (True) or the value false (False). Operands in a relational operator can be numeric types or types that can be reduced to numeric. Numeric types:

    • character - in relational operations, character codes are compared in accordance with the code table;
    • logical - the True and False values ​​are used, which take the values ​​1 - true and 0 - false, respectively;
    • string is a composite type consisting of a character type. Therefore, when strings are used, consecutive characters in two strings are compared.

    For example:

    5.6 > 7 - False;

    'P'< ‘Б’ — False;

    'Petrov' > 'Ivanov' - True;

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

    The result of logical operations will be the boolean values ​​True or False.

    Unary: NOT - negation.

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

    The operands of a boolean expression can only be boolean operations.

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

    A:='Ivanov'

    B:= ‘Alexander’

    Result: Ivanov Alexander.

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

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

    Operations priority levels:

    • operations of the first priority, are performed in the first place;
    • operations of the lowest priority are performed last;
    • operations with equal precedence are executed from left to right in the order in which they are written.

    At the same time, the compiler can sometimes reorder operands of the same priority. Parentheses are used to change the priority (increase it). The expression in parentheses is evaluated first, and then evaluated outside the parentheses.

    The lesson introduces the Boolean logical type in Pascal. An algorithm is considered for how to find minimum And maximum number in Pascal


    The site site provides laboratory tasks on the topic to consolidate the theoretical material and gain practical programming skills in Pascal. Brief theoretical information will allow you to get the minimum knowledge necessary for this. The solved illustrative examples and laboratory tasks are presented as their complexity increases, which will make 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 non-linear 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 ) ; (Will print True) end.

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

    To record the result of a logical expression, a special logical variable is used, which has a boolean type in Pascal 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); (Will print True) end.

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

    Example: Consider an example of working with the boolean type in pascal:

    var a:boolean; start 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 .

    Task Boolean 1. You are given a positive integer. Check the truth of the statement: "it is even"

    Consider 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"

    program Boolean; varx,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.

    Consider another solution to the problem in Pascal using a boolean variable:

    Boolean 2 task. Three integers are given: A, B, C. Check the truth of the statement: "B is between the numbers A and C."

    Consider solving a more complex problem with a boolean variable:

    Example: Given a three digit number. Check the truth of the statement: "All the digits of a 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 ; start 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; start 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 integer division operations 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 one.

    Boolean task 3. Given an integer N > 0 . Using the operations of division by integer and taking the remainder of the division, determine whether there is a number "2" in the record of the number N. If there is, then output TRUE , if not, output FALSE .

    Boolean task 4. Given a positive integer. Check the truth of the statement: "This number is an odd three-digit number."

    Minimum and maximum number in Pascal

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

    • Imagine the situation that we are frying pies, and have already fried a whole big hill; now we need to choose the largest of them, i.e. in our case, the maximum
    • We take the top pie, i.e. the first, and we say that it is the largest so far and put it aside.
    • Then we take the second and compare it with the largest, if this second pie turns out to be larger, we put it aside in the place of the “former largest” and say that now it is the largest.
    • We 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 it is said that it is necessary to find the maximum / minimum among positive numbers less than 1000, then:

    max:=0 min:= 1000 ;

    Boolean expressions (conditions) in Pascal, they are used in if statements and when organizing repetitions, namely in while and repeat-until loops.

    Examples of boolean expressions:

    1 . a > 2*b

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

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

    Logical expressions are built on the basis relation operations

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

    And logical operations

    and(logical and),

    or(logical or),

    not(logical negation),

    xor(exclusive or).

    result executing a boolean expression is a boolean value true(true) or false(lie). In complex logical expressions, arithmetic operations are performed first, then logical operations, and lastly, relational operations.

    24 pascal. Conditional if statement. Format and principle of action.

    The structure of the if 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 the<оператор1>, A<оператор2>ignored.

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

    Shorthand construction of the if statement

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

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

    if a< 2*b then begin

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

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

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

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

    Used when it is possible to 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 the logical expression is evaluated<условие>.

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

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

    25 pascal. case...of selection statement. Format and principle of action. Case selection statement

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

    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, except for real (usually a variable of type byte, integer, boolean or char);

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

    The else construct in the case statement may be absent.

    The case statement is executed as follows.

      The value of the selector expression is parsed.

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

    Any data - constants, variables, function values ​​are characterized in Pascal by a data type.

    Let's define the concept data type. As already known, all program objects (variables, constants, etc.) must be declared.

    Descriptions inform the translator, firstly, about the existence of the variables and other objects used, and secondly, indicate the properties of these objects. For example, the description of a variable whose value is a number indicates the properties of numbers. Formally, numbers can be integer and real (fractional). In Pascal, as in other programming languages, numbers are divided into two types: whole(reserved word integer) and real(reserved word real).

    The selection of integers as a separate type is explained by the fact that integers and real numbers are represented differently in a computer: an integer can be represented absolutely exactly, while a real number is inevitably represented with some finite error, which is determined by the properties of the translator.

    For example, let the variable x be of type real and its value is equal to one: x=1 . The corresponding value in computer memory can be 0.999999999 , 1.000000001 , or 1.000000000 . But if the variable x is declared as a variable of an integer type, then the unit will be represented in the computer absolutely exactly and the variable x will not be able to take real (fractional) values ​​- after all, it was declared as a variable of an integer type.

    So the data type defines:

    • internal representation of data in computer memory;
    • the set of values ​​that values ​​of this type can take;
    • operations that can be performed on values ​​of this type.

    The introduction of data types is one of the basic concepts of the Pascal language, which consists in the fact that when performing the operation of assigning the value of an expression to a variable, the variable and the expression must be of the same type. This check is performed by the compiler, which greatly simplifies the search for errors and increases the reliability of the program.

    The set of Turbo Pascal data types can be divided into two groups:

    • standard (predefined) types ;
    • user-defined types (user-defined types) .

    The standard types of Turbo Pascal include:

    • integer type - integer ;
    • real type - real ;
    • character type - char ;
    • boolean type - boolean ;
    • string type - string ;
    • pointer type - pointer ;
    • the text type is text .

    Custom data types are various combinations of standard types.

    Custom types include:

    • enumerated type;
    • interval type;
    • pointer type;
    • structured types;
    • procedural type.

    Comment. Another classification of data types is also possible, according to which types are divided into simple and complex.

    Simple types include: integer type, real type, character type, boolean type, enumerated type, and interval type.

    A complex type is various combinations of simple types (arrays, records, sets, files, etc.)

    Standard types

    The standard data type is defined by the Pascal language itself. When using standard types in a program, it is enough to indicate the subsections of the required types (const , var) and then describe the constants and variables used in the program. There is no need to use the Type subsection.

    For example, if the program uses only variables:

    i,j - integer (integers);

    x,y - real (real);

    t,s - char (character);

    a,b - boolean (logical),

    then only the variables subsection is needed - Var . Therefore, in the descriptive part of the program, variable declarations are written as follows:

    Integer types

    Data of this type can only take integer values. In a computer, values ​​of an integer type are represented exactly. If the variable is negative, then it must be preceded by the “-” sign; if the variable is positive, then the “+” sign can be omitted. This type is necessary in the case when some value cannot be represented approximately - a real number. For example, the number of people, animals, etc.

    Examples of writing integer values: 17, 0, 44789, -4, -127.

    The range of integer type data is determined by the five standard integer types and is presented in the table:

    Type Range Size in bytes
    Shortint -128...+128 1
    Integer -32768...32767 2
    Longint -2147483648...2147483647 4
    bytes 0...255 1
    Word 0...65535 2

    The last two types serve to represent only positive numbers, and the first three both positive and negative numbers.

    In the text of the program or when entering data of an integer type, values ​​are written without decimal point . Actual variable values must not exceed the allowable values of the type (Shortint , Integer , Longint , Byte , Word) that was used to describe the variable. Possible excesses in calculations are not controlled in any way, which will lead to incorrect operation of the program.

    An example of using an integer type variable

    var a:integer; b:word; c:byte; Begin a:=300; (a is set to 300) b:=300; (b set to 300) c:=200; (c is set to 200) a:=b+c; (a is set to 500) c:=b; (Error! Variable c can take values ​​no greater than 255. Here, variable c is assigned the value 500, which will cause the result to overflow.) End.

    Real types

    Values ​​of real types in a computer are represented approximately. The range of real type data is determined by five standard types: real (Real), with single precision (Single), double precision (Double), with increased precision (Extended), complex (Comp) and is presented in the table:

    Type Range Number of significant digits Size in bytes
    Real 2.9E-39...1.7E+38 11-12 6
    Single 1.5E-45...3.4E+38 >7-8 4
    Double 5E-324...1.7E+308 15-16 8
    Extended 3.4E-4951...1.1E+4932 19-20 10
    Comp -2E+63+1...+2E+63-1 19-20 8

    Real numbers can be represented in two formats: fixed and floating point.

    The format of a fixed-point number is the same as the usual mathematical notation for a decimal number with a fractional part. The fractional part is separated from the integer part with a dot, for example

    34.5, -4.0, 77.001, 100.56

    The floating point format is used when writing very large or very small numbers. In this format, the number before the "E" is multiplied by the number 10 to the power specified after the "E".

    1E-4 1*10-4
    3.4574E+3 3.4574*10+3
    4.51E+1 4.51*10+1

    Floating point examples:

    Number Writing in Pascal
    0,0001 1E-4
    3457,4 34574E-1
    45,1 451E-1
    40000 4E+4
    124 0.124E+3
    124 1.24E+2
    124 12.4E+1
    124 1240E-1
    124 12400E-2

    The table from 5 to 9 shows the entry of the same number 124. By changing the position of the decimal point in the mantissa (the point "floats", hence the name "recording a floating point number") and at the same time changing the exponent, you can choose the most appropriate entry numbers.

    Example of declaration of variables of real type.

    Character type

    Character type values ​​are characters that can be typed on a computer keyboard. This allows you to present text in the program and perform various operations on it: insert, delete individual letters and words, format, etc.

    The character type is denoted by the reserved word Char and is designed to store a single character. Character type data in memory occupies one byte.

    Symbolic variable declaration format:

    <имя переменной>:char;

    When defining the value of a character variable, the character is written in apostrophes. In addition, you can specify the required character by directly specifying its numerical value of the ASCII code. In this case, it is necessary to precede the number denoting the ASCII code of the required character with a # sign.

    An example of using character type variables:

    varc:char; (c is a character type variable) Begin c:='A'; (character 'A' is assigned to variable c) c:=#65; (variable c is also assigned the symbol A. Its ASCII code is 65) c:='5'; (variable c is assigned the character 5, End. here 5 is no longer a number)

    boolean type

    The logical data type is called Boolean after the English mathematician George Boole, the creator of the field of mathematics - mathematical logic.

    Boolean variable declaration format:

    <имя переменной>: boolean;

    Data of this type can take only two values:

    • True - true;
    • False - false.

    Boolean data is widely used in checking the validity of certain conditions and in comparing values. The result may be true or false.

    To compare data, the following relational operations are provided:

    An example of using relational operations:

    relation 5>3 , result true (true);

    relation 5=3 , the result is false (false).

    An example of using boolean variables.

    var a,b:boolean; (a,b are boolean variables) Begin a:=True; (variable a is set to true) b:=false; (variable b is set to false) End.

    Constants

    Integers, real numbers, symbols, character strings, logical constants can be used as constants.

    The constant must be declared in the descriptive part using the reserved word const.

    Constant declaration format

    Const<имя константы>= <значение>;

    If multiple constants are used in a program, only one Const keyword is allowed, and the description of each constant ends with a semicolon. The constant block ends with the declaration of another section or the declaration of a block of executable statements.

    Const (constant section declaration) year=2003; (constant of integer type, since there is no decimal point in the record) time=14.05; (real type constant) N=24; (constant of integer type, since there is no decimal point in the record) P=3.14; (real type constant) A=true; (boolean constant) str1='7'; (character type constant) str2='A'; (character type constant) str3='Turbo'; (string type constant) Var (variable section declaration) X,y:integer; (variables of integer type)

    Custom Types

    From the set of custom types, we will consider only

    • enumerated type;
    • interval type.

    We will need these two types when studying arrays.

    Enumerated type

    An enumerated data type describes new data types whose values ​​are defined by the programmer. An enumerated type is defined by enumerating the values ​​it can receive. Each value is named by some identifier and is located in a list enclosed in parentheses. An enumerated type is a user-defined data type, so its type declaration begins with the reserved word TYPE .

    Enumerated type format:

    <имя типа>= (constant1, constant2,..., constantN);

    Where
    constant1 , constant2 ,..., constantN is an ordered set of identifier values ​​treated as constants.

    An example of an enumerated type declaration:

    Type ball=(one, two, three, four, five); vart:ball;

    Here ball is the name of the enumerated type; one , two , three , four , five are constants; t is a variable that can take any value of constants.

    In an enumerated type, a constant is an identifier, so it is not quoted and cannot be a number. Thus, in an enumerated type, a constant is a special kind of constants that cannot be:

    • numeric type constants: 1, 2, 3, 4, etc.;
    • character type constants: "a", "s", "1", "3", etc.;
    • string type constants: "first", "second", etc.

    In addition, arithmetic operations and standard input and output procedures Read , Write are not applicable to values ​​of this type.

    An example of using variables of an enumerated type:

    Type days = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday); Var day: days; begin if day = Sunday then writeln('Today is Sunday!'); end.

    The elements in an enumerated type definition are considered ordered in the order in which they are listed. The numbering starts from zero. Therefore, in the above example, the days of the week have the following serial numbers

    To programmatically determine the sequence number, use the Ord() function.

    In our example, the serial numbers are equal:

    Ord(Monday) = 0;

    Ord(Saturday) = 5;

    Ord(Sunday) = 6.

    interval type

    If some variable does not take all the values ​​of its type, but only the values ​​contained in a certain range, then such a data type is called an interval type. Often, an interval type is called a bounded type and a range type. An interval type is defined by the boundaries of its values:

    <минимальное значение>..<максимальное значение>

    • two ".." characters are treated as one character, so no spaces are allowed between them;
    • the left end of the range must not exceed its right end.

    An interval type is a user-defined data type, so the declaration of this type begins with the keyword TYPE .

    An example of an interval type description:

    type digit = 1..10; month = 1..31; lat = 'A'..'Z';