Numeric data types in pascal. Data types in Pascal (variables, constants), their types and description

In Pascal variables are characterized by their type. A type is a property of a variable, according to which a variable can take on a set of values ​​allowed by this type, and participate in a set of operations allowed on this type.

A type defines the set of valid values ​​that a variable of a given type can take. It also defines the set of allowed operations from a variable of this type and defines the representation of data in the computer's RAM.

For example:

n:integer;

Pascal is a static language, which means that the type of a variable is determined when it is declared and cannot be changed. The Pascal language has a developed system of types - all data must belong to a previously known data type (either a standard type created during the development of the language or a user-defined type that the programmer defines). The programmer can create his types with an arbitrary complexity structure based on standard types, or types already defined by the user. The number of created types is unlimited. Custom types in the program are declared in the TYPE section by the format:

[name] = [type]

The standard type system has a branched, hierarchical structure.

Primary in the hierarchy are simple types. Such types are present in most programming languages ​​and are called simple, but in Pascal they have a more complex structure.

Structured types are built according to certain rules from simple types.

Pointers are formed from simple views and are used in programs to set addresses.

Procedural types are an innovation of the Turbo Pascal language, and they allow you to refer to subroutines as if they were variables.

Objects are also new, and they are intended to be used as an object-oriented language.

There are 5 types of integer types in Pascal. Each of them characterizes the range of accepted values ​​and their place in memory.

When using integer numbers, one should be guided by the nesting of types, i.e. smaller range types can be nested within larger range types. The Byte type can be nested in all types that occupy 2 and 4 bytes. At the same time, the Short Int type, which occupies 1 byte, cannot be nested in the Word type, since it does not have negative values.

There are 5 real types:

Integer types are exactly represented in a computer. Unlike integer types, the value of real types defines an arbitrary number only with some finite precision, depending on the format of the number. Real numbers are represented in a computer with fixed or floating point.

2358.8395

0.23588395*10 4

0.23588395*E 4

A special position in Pascal is occupied by the Comp type, in fact, it is a signed large integer. This type is compatible with all real types and can be used for large integers. When representing real floating-point numbers, the decimal point is always implied before the left or highest mantissa, but when operating on a number, it is shifted to the left or right.

Ordinal types

Ordinal types combine several simple types. These include:

  • all integer types;
  • character type;
  • boolean type;
  • type-range;
  • enumerated type.

Common features for ordinal types are: each type has a finite number of possible values; the value of these types can be ordered in a certain way and with each number a certain number, which is a serial number, can be compared; adjacent values ​​of ordinal types differ by one.

For ordinal type values, the ODD(x) function can be applied, which returns the ordinal number of the x argument.

Function PRED(x) - returns the previous value of the ordinal type. PRED(A) = 5.

SUCC(x) Function - Returns the next value of an ordinal type. SUCC(A) = 5.

Character type

Character type values ​​are 256 characters out of the set allowed by the code table of the computer being used. The initial area of ​​this set, i.e. the range from 0 to 127, corresponds to the set of ASCII codes where the characters of the alphabet, Arabic numbers and special characters are loaded. The start area characters are always present on the PC keyboard. The older area is called alternative, it contains characters of national alphabets and various special characters, and pseudographic characters that do not correspond to the ASCII code.

A character type value occupies one byte in RAM. In the program, values ​​are enclosed in apostrophes. Also, values ​​can be specified in the form of its ASCII code. In this case, the number with the character code must be preceded by a # sign.

C:= 'A'

Boolean (boolean) type

There are two values ​​of Boolean type: True (True) and False (False). Variables of this type are specified by the service word BOOLEAN. A Boolean value takes up one byte in RAM. The True and False values ​​correspond to the numeric values ​​1 and 0.

Type-range

There is a subset of its base type, which can be any ordinal type. The range type is defined by the boundaries within the base type.

[min-value]…[max-value]

The range type can be specified in the Type section as a specific type, or directly in the Var section.

When defining a range-type, one should be guided by:

  • the left border should not exceed the right border;
  • a range type inherits all the properties of the base type, but with limitations related to its lower cardinality.

Enumerated type

This type refers to ordinal types and is specified by listing those values ​​that it can enumerate. Each value is named by some identifier and is located in the list framed in parentheses. The enumerated type is specified in Type:

peoples = (men, women);

The first value is 0, the second value is 1, and so on.

Maximum power 65535 values.

string type

The string type belongs to the group of structured types and consists of the base type Char. The string type is not an ordinal type. It defines a set of character strings of arbitrary length up to 255 characters.

In the program, the string type is declared by the word String. Since String is a base type, it is declared in the language and the declaration of a variable of type String is done in Var. When declaring a string type variable behind String, it is advisable to indicate the length of the string in square brackets. Specifies an integer between 0 and 255.

Fam: String;

Specifying the string length allows the compiler to allocate the specified number of bytes in RAM for the given variable. If the string length is not specified, then the compiler will allocate the maximum possible number of bytes (255) for the value of this variable.

Federal Agency for Education

abstract

"DATA TYPES IN PASCAL"

1. Data types

Any data, i.e. constants, variables, properties, function values ​​or expressions are characterized by their types. A type defines the set of valid values ​​that an object can have, as well as the set of valid operations that can be applied to it. In addition, the type also determines the format of the internal representation of data in the PC memory.

In general, the Object Pascal language is characterized by a branched structure of data types (Fig. 1.1). The language provides a mechanism for creating new types, so that the total number of types used in the program can be arbitrarily large.

The data processed in the program is divided into variables, constants and literals:

Constants are data whose values ​​are set in the constant declaration section and do not change during program execution.

Variables are declared in the variable declaration section, but unlike constants, they get their values ​​already during the execution of the program, and these values ​​can be changed. Constants and variables can be referred to by name.

Literal has no identifier and is represented directly by the value in the program text.

Type defines the set of values ​​that data elements can take, and the set of operations allowed on them.

This and the four following chapters provide a detailed description of each type.

1.1 Simple types

Simple types include ordinal, real, and date-time types.

Ordinal types differ in that each of them has a finite number of possible values. These values ​​can be ordered in a certain way (hence the name of the types) and, therefore, each of them can be associated with some integer - the ordinal number of the value.

Real types, strictly speaking, also have a finite number of values, which is determined by the format of the internal representation of a real number. However, the number of possible values ​​of real types is so large that it is not possible to associate an integer (its number) with each of them.

date-time type designed to store date and time. In fact, it uses the real format for these purposes.

1.1.1 Ordinal types

Ordinal types include (see Figure 1.1) integer, boolean, character, enum, and range. For any of them, the Ord(x) function is applicable, which returns the ordinal number of the value of the expression X.


Rice. 1.1 - Structure of data types

For whole types, the function ord(x) returns the value of x itself, that is, Ord(X) = x for x belonging to any whole type. Applying Ord(x) to logical , symbolic and enumerated types gives a positive integer in the range 0 to 1 ( boolean type), from 0 to 255 ( symbolic), from 0 to 65535 ( enumerable). Type-range preserves all the properties of the underlying ordinal type, so the result of applying the ord(x) function to it depends on the properties of that type.

Functions can also be applied to ordinal types:

predict(x)- returns the previous value of the ordinal type (the value that corresponds to the ordinal ord (x) -1, i.e. ord(pred(x)) = ord(x) - 1;

succ(x)- returns the next value of the ordinal type that corresponds to the ordinal ord(x) + 1, i.e. ord(Succ(x)) = ord(x) + 1.

For example, if the program defines a variable

then the PRED(c) function will return the character "4" and the SUCC(c) function will return the character "6".

If we think of any ordinal type as an ordered set of values ​​increasing from left to right and occupying a certain segment on the number axis, then the function pred (x) is not defined for the left end, and succ (x) - for the right end of this segment.

Integer types . The range of possible values ​​for integer types depends on their internal representation, which can be one, two, four, or eight bytes. In table. 1.1 lists the names of integer types, the length of their internal representation in bytes, and the range of possible values.

Table 1.1 - Integer types

Name Length, bytes Value range
cardinal 4 0. .. 2 147 483 647
bytes 1 0...255
Shortint 1 -128...+127
Smallint 2 -32 768...+32 767
Word 2 0...65 535
Integer 4
Longint 4 -2 147 483 648...+2 147 483 647
int64 8 -9*1018...+9*1018
long word 4 0. . .4 294 967 295

Types long word and int64 first introduced in version 4, and types Smallint and cardinal missing in Delphi 1. Type integer for this version, it takes 2 bytes and has a range of values ​​from -32768 to +32767, i.e., the same as Smallint .

When using procedures and functions with integer parameters, one should be guided by the “nesting” of types, i.e. wherever it can be used word, it is allowed to use bytes(but not vice versa) Longint“enters” Smallint, which in turn includes Shortint .

The list of procedures and functions applicable to integer types is given in Table. 1.2. Letters b, s, w, i, l denote expressions, respectively, of the type bytes , Shortint, Word, Integer and Longint ,

x is an expression of any of these types; the letters vb, vs, vw, vi, vl, vx denote variables of the respective types. An optional parameter is indicated in square brackets.

Table 1.2 - Standard Procedures and Functions Applicable to Integer Types

Appeal Result type Action
abs(x) x Returns module x
chr(b) Char Returns a character by its code
dec(vx[, i]) - Decreases the value of vx by i, and in the absence of i - by 1
inc(vx[,i]) - Increases the value of vx by i, and in the absence of i - by 1
Hi(w) bytes Returns the highest bow of the argument
Hi(I) Same Returns the third byte
Lo(i) Returns the low byte of the argument
Lo(w) Same
odd(l) Boolean Returns True if the argument is an odd number
Random(w) As parameter Returns a pseudo-random number evenly distributed in the range 0...(w-l)
sqr(x) X Returns the square of the argument
swap(i) Integer Swap bytes in a word
swap(w) Word Too

When operating on integers, the type of the result will correspond to the type of the operands, and if the operands are of different integer types, to the general type that includes both operands. For example, when acting with shortint and word common will be the type integer. By default, the Delphi compiler does not generate code that controls whether a value is out of range, which can lead to confusion.

Boolean types . Boolean types are Boolean, ByteBool, Bool, wordBool and longbool. In standard Pascal, only the type is defined Boolean, other Boolean types are introduced in Object Pascal for compatibility with Windows: types Boolean and ByteBool occupy one byte each, Bool and wordbool- 2 bytes, longbool- 4 bytes. Boolean values ​​can be one of the pre-declared constants False (false) or True (true).

Since the Boolean type is an ordinal type, it can be used in a counting type loop statement. In Delphi 32 for Boolean meaning

Ord (True) = +1, while for other types ( bool, wordbool etc.)

Ord (True) = -1, so these kinds of operators should be used with care! For example, for version Delphi 6, the executable showMessage (" ---") statement in the following loop for will never be executed:

for L:= False to True do

ShowMessage("--);

If we replace the loop parameter type L in the previous example with Boolean, the loop will run and the message will appear twice on the screen. [For Delphi version 1 and 2 ord (True) =+1 for any boolean type.]

Character type . Character type values ​​are the set of all PK characters. Each character is assigned an integer in the range 0...255. This number serves as the code for the internal representation of the character, and is returned by the ord function.

Windows encoding uses ANSI code (named for the American National Standard Institute, the American standards institute that proposed this code). The first half of PC characters with codes 0...127 corresponds to Table 1.3. The second half of characters with codes 128...255 changes for different fonts. The standard Windows fonts Arial Cyr, Courier New Cyr and Times New Roman to represent Cyrillic characters (without the letters “ё” and “Ё”) use the last 64 codes (from 192 to 256): “А”... “Я” are encoded values ​​192..223, “a”... “i” - 224...255. The characters "Ё" and "ё" have codes 168 and 184, respectively.

Table 1.3 - Character encoding according to the ANSI standard

The code Symbol The code. Symbol The code. Symbol The code Symbol
0 NUL 32 BL 64 @ 96 "
1 ZON 33 ! 65 AND 97 a
2 STX 34 66 AT 98 b
3 ETX 35 # 67 FROM 99 With
4 EOT 36 $ 68 D 100 d
5 ENQ 37 % 69 E 101 e
6 ACK 38 & 70 F 102 f
7 BEL 39 " 71 G 103 d
8" BS 40 ( 72 H 104 h
9 HT 41 ) 73 I 105 i
10 LF 42 * 74 J 106 j
11 VT 43 + 75 To 107 k
12 FF 44 F 76 L 108 1
13 CR 45 - 77 M 109 m
14 SO 46 78 N 110 n
15 SI 47 / 79 0 111 about
16 DEL 48 0 80 R 112 P
17 DC1 49 1 81 Q 113 q
18 DC2 50 2 82 R 114 r
19 DC3 51 3 83 S 115 s
20 DC 4 52 4 84 T 116 t
21 NAK 53 5 85 U 117 u
22 SYN 54 6 86 V 118 v
23 ETB 55 7 87 W 119 W
24 CAN 56 8 88 X 120 x
25 EM 57 9 89 Y 121 At
26 SUB 58 : 90 Z .122 z
27 ESC 59 ; 91 t 123 {
28 FS 60 < 92 \ 124 1
29 GS 61 = 93 ] 125 }
30 RS 62 > 94 L 126 ~
31 US 63 F 95 127 r

Symbols with codes 0...31 refer to service codes. If these codes are used in the symbolic text of a program, they are considered spaces.

most common in mathematics numeric types- this is whole numbers that represent an infinite number of discrete values, and valid numbers that represent an unlimited continuum of values.

Description of numeric data types (integers) Pascal

Within the same language, different subsets of the set of integers can be implemented. The range of possible values ​​of integer numeric types depends on their internal representation, which can be one, two, or four bytes. So, Pascal 7.0 uses the following integer numeric data types:

With whole numeric data types Pascal can perform the following operations:

  • Arithmetic:
    addition(+);
    subtraction(-);
    multiplication(*);
    remainder of division (mod);
    exponentiation;
    unary plus (+);
    unary minus (-).
  • Relationship operations:
    equality relation (=);
    inequality relation (<>);
    ratio less (<);
    ratio greater than (>);
    ratio not less than (>=);
    ratio no more (<=).

When acting with integer numeric data types the type of the result will correspond to the type of the operands, and if the operands are of different integer types, to the type of the operand that has the maximum cardinality (maximum range of values). Possible result overflow is not controlled in any way (it is important!) , which can lead to errors.

Particular attention should be paid to the division operation of integer numeric data types. In Pascal, two division operations are allowed, which are respectively denoted "/" and div. You need to know that the result of dividing "/" is not an integer, but real number(this is true even if you divide 8 by 2, i.e. 8/2=4.0). The div division is integer division, i.e. integer result type.

Description of numeric data types (real) Pascal

The real numeric data type refers to a subset of real numbers that can be represented in a so-called floating point format with a fixed number of digits. With floating point, each numeric data type is represented as two groups of digits. The first group of digits is called the mantissa, the second - the order. In general, a numeric data type in floating point form can be represented as follows: X= (+|-)MP (+ | -) r , where M is the mantissa of the number; r is the order of the number (r is an integer); P is the base of the number system. For example, for a decimal base, the representation of 2E-1 (here E is the base of the decimal number system) will look like: 2*10 -1 =0.2, and the representation of 1.234E5 will correspond to: 1.234*10 5 =123400.0.

Pascal uses the following types of real numbers, which define an arbitrary number only with some finite precision, depending on the internal format of the real number:

When describing a real variable of the real type, a 4-byte variable will be created in the computer's memory. In this case, 3 bytes will be given under the mantissa, and one - under the order.

You can perform the following operations on real numeric data types:

  • Arithmetic:
    addition (+);
    subtraction(-);
    multiplication(*);
    division(/);
    exponentiation;
    unary plus (+);
    unary minus (-).
  • Relationship operations:
    inequality relation (<>);
    ratio less (<);
    ratio greater than (>);
    ratio not less than (>=);
    ratio no more (<=).

As you can see, Pascal is characterized by a rich range of real types, but access to numeric data types single, double and extended only possible under special compilation modes. These numerical data types are designed for hardware support of floating point arithmetic and for their effective use, the PC must include a mathematical coprocessor.

A special position in Pascal is occupied by a numeric data type. comp, which is treated as a real number without exponential and fractional parts. Actually, comp is a signed "big" integer that stores 19..20 significant decimal digits. At the same time, the numeric data type comp in expressions, it is fully compatible with other real types: all real operations are defined on it, it can be used as an argument of mathematical functions, etc.

About converting numeric data types in Pascal

Implicit (automatic) conversions of numeric data types are almost impossible in Pascal. An exception is made only for the type integer, which is allowed to be used in expressions like real. For example, if the variables are declared as follows:

VarX: integer; Y: real

Then the operator

will be syntactically correct, although an integer expression is to the right of the assignment sign, and a real variable is to the left, the compiler will do the conversion of numeric data types automatically. The reverse conversion is automatically type real per type integer is not possible in Pascal. Let's remember how many bytes are allocated for variables like integer and real: under integer data type integer 2 bytes of memory are allocated, and under real - 6 bytes. For conversion real in integer there are two built-in functions: round(x) rounds a real x to the nearest integer, trunc(x) truncates a real number by discarding the fractional part.

LECTURE 2

Basics of programming.

Introduction to Pascal. Data types. Operations.

Language alphabetPascal

Any natural language consists of such elements as symbols, words, phrases, sentences. The programming language also has similar elements: symbols, words, expressions (phrases), operators (sentences).

Words are formed from a collection of characters. Expressions - are groups of words, and operators - These are combinations of words and expressions. Symbols of the language - there are elementary signs (letters) that are used to compose some texts. So, the set of these characters forms the alphabet of the language.

The Pascal language alphabet consists of:

1.uppercase and lowercase letters of the Latin alphabet, which includes the following characters:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - capital letters;

A b c d e f g h i j k l m n o p q r s t u v w x y z - lowercase letters;

2. decimal Arabic numerals: 0 1 2 3 4 5 6 7 8 9;

3. hexadecimal digits (constructed from decimal digits and letters from A to F);

4. 32 uppercase and lowercase letters of the Russian alphabet;

5. special characters:

Combinations of special characters can form compound characters:

:= assignment;

< >not equal;

>= greater than or equal;

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

Range of values;

(* *) or ( ) - comment.

Structure of a Pascal program

In order for the Pascal compiler to correctly understand exactly what actions are expected of it, your program must be formatted in full accordance with the syntax (rules for constructing programs) of this language.

Any Pascal program can consist of the following blocks (square brackets here and below mark optional parts):

program<имя_программы>;

[ uses<имена_подключаемых_модулей>;]

[ label<список_меток>;]

[ const<имя_константы> = <значение_константы>;]

[ type<имя_типа> = <определение_типа>;]

[var<имя_переменной> : <тип_переменной>;]

[procedure<имя_процедуры> <описание_процедуры>;]

[ function<имя_функции> <описание_функции>;]

begin (beginning of the main body of the program)

<операторы>

end. (* end of main program body *)

Later versions of Pascal compilers no longer require the name of the program to be specified, that is, the string program<имя_программы>; can be omitted. But this is possible only if the entire program is contained in one module-file. If the program consists of several independent pieces - modules, then each of them must have a heading (program or unit).

Any of the listed optional sections can occur more than once in the program text, their general sequence can also change, but the main rule of the Pascal language must always be fulfilled: before an object is used, it must be declared and described.

Pascal compilers do not distinguish between lowercase and uppercase letters, and whitespace characters are ignored, so the program text can be structured in such a way that it is most convenient to read and debug it.

Compiler directives

The line that starts with the symbols ($) is not a comment, but a compiler directive - a special command on which the process of compiling and executing a program depends. We will consider directives in those sections to which they refer "by meaning".

For example, the line ($I-,Q+) disables I/O validation, but enables overflow during computation.

Identifiers

The names given to program objects (constants, types, variables, functions and procedures, and the entire program as a whole) are called identifiers. They can only consist of numbers, Latin letters and the "_" sign (underscore). However, a number cannot start a name. Identifiers can be of any length, but if two names have the same first 63 characters, then such names are considered identical.

You can give program objects any names, but it is necessary that they differ from the reserved words used by the Pascal language, because the compiler will not accept variables with "foreign" names anyway.

Here is a list of the most common reserved words:

array implementation shl

case interface string

const label then

file pointer uses

far procedure var

for program while

forward record with

function repeat xor

Variables and data types

A variable is a program object whose value can change during the course of the program.

A data type is a characteristic of the range of values ​​that variables of that data type can take.

All variables used in the program must be declared in a special var section according to the following pattern:

var<имя_переменной_1> [, <имя_переменной_2, _>] : <имя_типа_1>;

<имя_переменной_3> [, <имя_переменной_4, _>] : <имя_типа_2>;

The Pascal language has a large set of various data types, but for now we will indicate only a few of them. We will talk about all data types further.

Constants

A constant is an object whose value is known before the program starts.

Constants are necessary for the design of visual programs, are indispensable when using repeatedly repeated values ​​​​in the text of the program, and are convenient if you need to change these values ​​​​at once in the entire program.

There are three kinds of constants in Pascal:

Unnamed constants (numbers and numbers, characters and strings, sets);

Named untyped constants;

Named typed constants.

Unnamed Constants

Unnamed constants do not have names and therefore do not need to be declared.

The type of an unnamed constant is determined automatically, by default:

Any sequence of digits (perhaps preceded by a "-" or "+" sign or separated by a single dot) is perceived by the compiler as an unnamed constant - a number (integer or real);

Any sequence of characters enclosed in apostrophes is treated as an unnamed constant - a string;

Any sequence of integers or characters separated by commas, framed by square brackets, is perceived as an unnamed constant - a set.

In addition, there are two special constants true and false that refer to the boolean data type.

Examples of the use of unnamed constants are the following operators:

real2:= 12.075 + x;

string4:= "abc" + string44;

set5:=*set55;

boolean6:=true;

Untyped Constants

Named constants, as their name suggests, must have a name. Therefore, these names must be reported to the compiler, that is, described in a special const section.

If you do not specify the type of the constant, then by its appearance the compiler will determine which (base) type it belongs to. Any constant already described can be used when declaring other constants, variables, and data types. Here are some examples of declaring untyped named constants:

Typed Constants

Typed named constants are variables (!) with an initial value that is already known by the time the program starts. Therefore, firstly, typed constants cannot be used to define other constants, data types, and variables, and secondly, their values ​​can be changed during program operation.

Typed constants are described according to the following pattern:

const<имя_константы> : <тип_константы> = <начальное_значение>;

The examples below show how to do this:

const n: integer = -10;

b:boolean=true;

We will give examples of typed constants of other types as we study the corresponding data types.

Pascal Data Types

Pascal compilers require that information about the amount of memory required for a program to run be provided before the program can run. To do this, in the variable declaration section (var), you need to list all the variables used in the program. In addition, you must also tell the compiler how much memory each of these variables will take up.

All this can be told to the program by simply specifying the type of the future variable. Having information about the type of a variable, the compiler "understands" how many bytes should be allocated for it, what actions can be performed with it, and in what constructions it can participate.

For the convenience of programmers in the Pascal language, there are many standard data types and, in addition, the ability to create new data types based on existing ones (standard or again defined by the programmer), which are called constructed.

The division into basic and constructed data types in the Pascal language is shown in the table:

Ordinal (discrete) data types

Address data types

Structured Data Types

Arithmetic Data Types

Basic data types

Logical

Symbolic

Real

Netipizi

fixed pointer

Constructed types

enumerable

week = (su, mo, tu, we, th, fr, sa);

Typed Pointer

array

string

record

Procedural

Object

Interval (range)

Data Types Constructed by the Programmer

Ordinal data types

Ordinal types stand out among the basic data types. This name can be justified in two ways:

1. Each element of an ordinal type can be associated with a unique (ordinal) number. Numbering of values ​​starts from zero. The exception is the shortint, integer, and longint data types. Their numbering coincides with the values ​​of the elements.

2. In addition, on elements of any ordinal type, an order is defined (in the mathematical sense of the word), which directly depends on the numbering. Thus, for any two elements of an ordinal type, it is possible to say exactly which of them is less and which is greater.

Routines that handle ordinal data types

The following functions and procedures are defined only for values ​​of ordinal types:

1. The ord(x) function returns the ordinal number of the value of the variable x (relative to the type to which the variable x belongs).

2. The pred(x) function returns the value preceding x (not applicable to the first element of the type).

3. The succ(x) function returns the value following x (not applicable to the last element of the type).

4. The procedure inc(x) returns the value following x (for arithmetic data types, this is equivalent to the operator x:=x+1).

5.The procedure inc(x,k) returns the kth value following x (for arithmetic data types, this is equivalent to the operator x:=x+k).

6. The procedure dec(x) returns the value preceding x (for arithmetic data types, this is equivalent to the operator x:=x-1).

7. The procedure dec(x,k) returns the kth value preceding x (for arithmetic data types, this is equivalent to the operator x:=x-k).

At first glance, it seems that the result of applying the inc(x) procedure is exactly the same as the result of using the succ(x) function. However, the difference between them appears at the boundaries of the acceptable range. The succ(x) function is not applicable to the maximum element of the type, but the inc(x) procedure will not give any error, but, acting according to the rules of machine addition, will add the next one to the element number. The number, of course, will go out of range and, due to truncation, will turn into the number of the minimum value of the range. It turns out that the procedures inc () and dec () perceive any ordinal type as if "closed in a ring": immediately after the last, the first value again comes.

Let's explain everything that has been said with an example. For data type

type sixteen = 0..15;

trying to add 1 to the number 15 will result in the following result:

The initial unit will be cut off, and therefore it will turn out that inc(15)=0.

A similar situation at the lower bound of the allowable range of an arbitrary ordinal data type is observed for the dec(x) procedure and the pred(x) function:

dec(min_element)=max_element

Ordinal Data Types

1. The logical type boolean has two values: false and true, and the following equalities hold for them:

ord(false)=0, ord(true)=1, false

predict(true)=false, succ(false)=true,

inc(true)=false, inc(false)=true,

dec(true)=false, dec(false)=true.

2. The character type char includes 256 extended ASCII characters (for example, "a", "b", "i", "7", "#"). The character number returned by the ord() function is the same as that character's number in the ASCII table.

3. Integer data types are summarized in a table:

Data type

Number of bytes

Range

2147483648..2147483647

4. Enumerated data types are specified in the type section by an explicit enumeration of their elements. For example:

type week =(sun,mon,tue,wed,thu,fri,sat)

Recall that for this data type:

inc(sat) = sun, dec(sun) = sat.

5. Interval data types are set only by the boundaries of their range. For example:

type month = 1..12;

weekday = mon..fri;

6. Data types constructed by the programmer are described in the type section according to the following template:

type<имя_типа> = <описание_типа>;

For example:

type lat_bukvy = "a".."z","A".."Z";

The base data types are standard, so there is no need to describe them in the type section. However, this can also be done if desired, for example by giving long definitions short names. Let's say by introducing a new data type

type int = integer;

you can shorten the text of the program a little.

Real data types

Recall that these data types are arithmetic, not ordinal.

Data type

Number of bytes

Range (absolute value)

1.5*10-45..3.4*1038

2.9*10-39..1.7*1038

5.0*10-324..1.7*10308

3.4*10-4932..1.1*104932

Constructed Data Types

These data types (along with the operations defined for them) will be discussed later in several lectures.

Operations and Expressions

Arithmetic operations

Let's talk about operations - standard actions allowed for variables of one or another basic data type. The basis will be arithmetic and logical operations.

Note: All of the following operations (with the exception of the unary "-" and not) require two operands.

1. Logical operations (and - logical AND, or - logical OR, not - logical NOT, xor - exclusive OR) are applicable only to boolean values. They also result in boolean values. Here are tables of values ​​for these operations:

true false true

false false false

true false false

2. Comparison operations (=,<>, >, <, <=, >=) apply to all base types. Their results are also boolean values.

3. Integer arithmetic operations are applicable only to integer types. Their result is an integer whose type depends on the types of the operands.

a div b - integer division of a by b (probably no need to remind you that division by 0 is forbidden, so the operation throws an error in such cases). The result will be of a data type common to the types to which the operands belong.

For example, (shortint div byte = integer). This can be explained as follows: integer is the minimum type, of which both byte and shortint are subsets.

a mod b - taking the remainder when dividing a by b as a whole. The type of the result, as in the previous case, is determined by the types of the operands, and 0 is a forbidden value for b. Unlike the mathematical operation mod, which always results in a non-negative number, the sign of the result of the "programming" operation mod is determined by the sign of its first operand. Thus, if in mathematics (-2 mod 5) = 3, then we have (-2 mod 5) = -2.

a shl k - shift the value of a by k bits to the left (this is equivalent to multiplying the value of variable a by 2k). The result of the operation will be of the same type as its first operand(s).

a shr k - shift the value of a by k bits to the right (this is equivalent to dividing the value of variable a by 2k by 2k). The result of the operation will be of the same type as its first operand(s).

and,or,not,xor - binary arithmetic operations that work with bits of the binary representation of integers, according to the same rules as their corresponding logical operations.

4. General arithmetic operations (+, -, *, /) are applicable to all arithmetic types. Their result belongs to the data type common to both operands (the only exception is the fractional division operation /, whose result is always of the real data type).

Other operations

There are other operations specific to the values ​​of some standard Pascal data types. These operations will be discussed in the relevant sections:

#, in, +, *, : see lecture 5 “Symbols. Strings. Sets»

@, ^ : see Lecture 7 "Addresses and Pointers"

Standard arithmetic functions

Standard arithmetic functions are also adjacent to arithmetic operations. Their list with a brief description is given in the table.

Function

Description

Argument type

Result type

Absolute value (modulus) of a number

Arithmetic

Matches the argument type

Arctangent (in radians)

Arithmetic

Real

Cosine (in radians)

Arithmetic

Real

Exhibitor (ex)

Arithmetic

Real

Taking the fractional part of a number

Arithmetic

Real

Taking the integer part of a number

Arithmetic

Real

Natural logarithm (base e)

Arithmetic

Real

Checking odd number

Number value

Real

Rounding to nearest integer

Arithmetic

Rounding "down" - to the nearest smaller integer

Arithmetic

Sine (in radians)

Arithmetic

Real

Squaring

Arithmetic

Real

Extracting the square root

Arithmetic

Real

Arithmetic expressions

All arithmetic operations can be combined with each other - of course, taking into account the data types allowed for their operands.

The operands of any operation can be variables, constants, function calls, or expressions built on the basis of other operations. All together is called an expression.

Examples of arithmetic expressions:

(x<0) and (y>0) - an expression whose result is of type boolean;

z shl abs(k) - the second operand is a standard function call;

(x mod k) + min(a,b) + trunc(z) - combination of arithmetic operations and function calls;

odd(round(x/abs(x))) - "multi-story" expression.

Calculation order

If brackets are placed in the expression, then the calculations are performed in the order: the smaller the nesting depth of the brackets, the later the operation enclosed in them is calculated. If there are no parentheses, then the values ​​of operations with a higher priority are calculated first, then those with a lower one. Several consecutive operations of the same priority are calculated in sequence "from left to right".

Table 2.1. Priorities (for all) Pascal operations

Knowing and understanding data types is an essential part of programming.

In this lesson, we will get acquainted with data types in the Turbo Pascal programming language.

In the Pascal language, any objects, i.e. constants, variables, function values ​​or expressions are characterized by their types. A type defines a set of valid values ​​for an object, as well as a set of operations that can be applied to it. In addition, the type determines the format of the internal representation of data in the computer's memory. With respect to object types, Pascal is a static language. This means that the type of an object, such as a variable, is determined when it is declared and cannot be changed later.

Structure of data types in Pascal language:

Simple language types
Simple types include ordinal, real, string, and address (pointer) types. All of them define the type of only one single value.

Ordinal types are characterized by the fact that each of them has a finite number of possible values, among which a linear order is established. Each of the values ​​can be associated with some integer - its ordinal number.

Integer types- denote sets of integers in different ranges. There are five integer types, differing in the range of valid values ​​and the amount of RAM they use. Integer types are denoted by identifiers: Byte, ShortInt, Word, Integer, LongInt; their characteristics are given in the following table.

Values ​​of integer types are written in the program in the usual way:
123 4 -3 +345 -699
The presence of a decimal point in the notation of an integer is not allowed. It would be an error to write an integer like this:
123.0
In addition to the usual decimal notation, integers can be written in hexadecimal format using the $ prefix, for example:
$01AF $FF $1A $F0A1B
The case of the letters A,B, ..., F does not matter.

Allowed operations:

  • - assignment;
  • - all arithmetic: +, - ,*, /, div, mod (with normal division [/] the result is real!);
  • - comparison<, >, >=, <=, <>, =.
Boolean type (Boolean)- consists of only two values: False (false) and True (true). The words False and True are defined in the language and are, in fact, logical constants. The case of letters in their spelling is not significant: FALSE = false. Values ​​of this type are the result of evaluation of conditional and logical expressions and participate in all kinds of conditional statements of the language.
Allowed operations:
  • - assignment;
  • - comparison:<, >, >=, <=, <>, =;
  • - logical operations: NOT, OR, AND, XOR
Character type (Char) is a data type consisting of a single character (sign, letter, code). A Char value can be any character from the ASCII character set. If the symbol has a graphical representation, then in the program it is written enclosed in single quotes (apostrophes), for example:
"g" "s" "." "*" ""-(space)
To represent the apostrophe itself, its image is doubled: """".
If the character does not have a graphical representation, for example, a tab character or a carriage return character, then you can use the equivalent notation of the character value, consisting of the # prefix and the ASCII code of the character:
#9 #32 #13
Allowed operations:
  • - assignment;
  • - comparison:<, >, >=, <=, <>, =. A large character is one that has a higher ASCII number.
String type (String, String[n])- this data type defines character sequences - strings. The n parameter specifies the maximum number of characters per line. If not specified, n=255 is assumed. A value of type "string" in the program is written as a sequence of characters enclosed in single quotes (apostrophes), for example
"This is a string"
"1234" is also a string, not a number
"" - empty line

Allowed operations:
  • - assignment;
  • - addition (concatenation, merging); for example, S:= "Winter"+" "+"came!";
  • - comparison:<, >, >=, <=, <>, =. Strings are considered equal if they have the same length and are character-by-character equivalent.
Real types- denote sets of real numbers in different ranges. There are five real types, differing in the range of valid values ​​and the size of the occupied RAM. Real types are denoted by identifiers: Real, Single, Double, Extended, Comp; their characteristics are given in the following table.

Comp type although it refers to real types, it is actually integer with a very huge range of values.
Values ​​of real types can be written in the program in several ways:
1.456 0.000134 -120.0 65432
+345 0 -45 127E+12
-1.5E-5 -1.6E+12 5E4 0.002E-6

It would be an error to write a real number like this:
.5 (correct 0.5)
12. (correct 12.0 or 12)

A real number in floating point form (exponential form) is written as a pair
<мантисса>E<порядок>
Such a designation is understood as "the mantissa multiplied by ten to a power equal to the order." For example,
-1.6E+12 corresponds to -1.6 1012

Allowed operations:
- assignment;
- all arithmetic: +, -, *, /;
- comparison:<, >, >=, <=, <>, =.

When comparing real numbers, it should be remembered that due to the inaccuracy of their representation in computer memory (in view of the inevitability of rounding), attempts to determine the strict equality of two real values ​​should be avoided. There is a chance that the equality will turn out to be false, even if in fact it is not.

A range or (restricted type) is not a predefined language type (such as Integer or Char, for example) and therefore has no corresponding identifier. This type is user-input. Using it, we can define a new type that will only contain values ​​from a limited subrange of some base type. The base type can only be an integer type, a Char (character) type, and any of the enumerated types introduced by the programmer.

To introduce a new type - a range - in the TYPE type description block, specify the name of the type being introduced and the boundaries of the range through the special character of the range ".." (two dots in a row):
TYPE
Century = 1..21; (subrange of integer type)
CapsLetters = "A".."I"; ( subrange of type Char )

Structured language types

Structured types include: array, record, set, file, etc. All of them define the type (or types) of some data structure.

array- an ordered structure of the same type of data that stores them sequentially. An array must have dimensions that determine how many elements are stored in the structure. Any element in an array can be accessed by its index.

The array type is defined by the construct:
Array [range] of ItemType;

The range in square brackets specifies the index values ​​of the first and last element in the structure. Examples of type and variable declarations:

TYPE Vector = array of Real; VAR V1: Vector; V2: array of Bytes;
Here the variable V1 is defined using the Vector type described above; the type of the variable V2 is constructed directly at the stage of its description.

You can also specify an array as the type of array elements, thus forming multidimensional structures. For example, the description of a two-dimensional structure (matrix) will look like this:
VAR M1: array of array of Byte; The same can be written much more compactly: VAR M2: array of Byte;
Here the arrays M1 and M2 have exactly the same structure - a 3x3 square matrix.

An array element is accessed by specifying its index, for example:

WriteIn(V1); (displaying the first element of the array V1) readln(M2); (inputting the third element of the second row of the matrix M2)
This concludes the lesson on data types, the text was almost completely copied and pasted (the link will be below), because I do not see the point of telling this material in my own words. If the difference between data types is at least a little clear, then this is already good.