Integer data types in pascal. Pascal. Simple data types

Basics of programming
Every professional was once a teapot. Surely you are familiar with the state when “you don’t know how to start thinking in order to come up with such a thing.” You've probably encountered a situation where you just don't know where to start. This book is aimed precisely at such people who would like to become a programmer, but have absolutely no idea how to start this path.

...

Almost all integer data types are . These data types represent integers within a certain range. The specific names of integer types and ranges of values ​​depend on the specific programming language, the compiler, and the compilation mode. You can learn more about this in the compiler documentation. For example, data type Integer For example, data type in Delphi it has a range of -2147483648…2147483647, while in Turbo Pascal the data type For example, data type represents numbers in the range -35768…32767. In Free Pascal, the range of values ​​of type

determined by the selected mode.

Since Lazarus uses the Free Pascal compiler, everything said about data types in relation to Free Pascal is also true for Lazarus.

So, Free Pascal's integer data types are listed in Table 13.1.

Table 13.1. Free Pascal Integer Data Types (Lazarus). Type Size, bytes
Range of values 1 0…255
Byte 1 -128…127
Shortint 2 -35768…32767
Smallint 2 0…65535
For example, data type Word 2 or 4
Depends on compilation mode 4 0…4294967295
Cardinal 4 -2147483648…2147483647
Longint 4 0...4294967295
Longword 8 -9223372036854775808...9223372036854775807
Int64 8 0...18446744073709551615

QWord
NOTE Longword Types in Free Pascal Int64 And

are not! This means that you cannot use them, for example, for index variables in loops. However, I presented them here so as not to describe them separately in the future and to collect all Free Pascal integer types in one place. If you don’t understand some words, don’t be alarmed. In due time I will tell you about everything in more detail.

And now a few explanations about the table. In a collumn TYPE

And now a few explanations about the table. data type identifiers are given (keywords that indicate to the compiler what type a particular data belongs to). You will learn how to use these identifiers in the following lessons. SIZE Range of values, Smallint, Depends on compilation mode indicates the size that the data type occupies in computer memory. For example, a positive integer can be represented by different types: Depends on compilation mode etc. However, a number like Range of values– only 1 byte. Therefore, if you know for sure that the number you are working with will never take a value greater than 255, then it is better to define it as a type Range of values, as this will save space in your computer's memory. Although not everything is so simple here (the nuances of the distribution of memory and other computer resources are beyond the scope).

And now a few explanations about the table. RANGE specifies the range of values ​​that the data type operates on. For example, a number like Range of values can take values ​​from 0 to 255.

Now for practice. Let's write a program that displays the ranges of values ​​of all integer data types. The source code for this program is given below:

Listing 13.1. A program for displaying ranges of integers. program td; ($mode objfpc)($H+) uses ($IFDEF UNIX)($IFDEF UseCThreads) cthreads, ($ENDIF)($ENDIF) Classes ( you can add units after this ); begin Writeln("Byte: ", Low(Byte), "..", High(Byte));

Writeln("Shortint: ", Low(Shortint), "..", High(Shortint)); Writeln("Smallint: ", Low(Smallint), "..", High(Smallint)); Writeln("Word: ", Low(Word), "..", High(Word)); Writeln("Integer: ", Low(Integer), "..", High(Integer)); Writeln("Cardinal: ", Low(Cardinal), "..", High(Cardinal)); Writeln("Longint: ", Low(Longint), "..", High(Longint)); Types in Free Pascal Writeln("Longword: ", Low(Longword), "..", High(Longword)); Writeln("Int64: ", Low(Int64), "..", High(Int64));

Writeln("QWord: ", Low(QWord), "..", High(QWord));

10
178
35278

Readln; end.

Standard function

  1. Low defines the minimum value of the data type. Funtskia
  2. High defines the maximum value. With functions
  3. WriteLn ReadLn
  4. you already know each other a little. We will talk in more detail about subroutines (procedures and functions) in the corresponding section. Finally, I’ll tell you how integer data is written in the program. Yes, just like everywhere else - just write the number, without quotes or any additional symbols. For example, like this

True, this applies to numbers in the decimal number system. Surely you already know that there are other systems. The most widely used number systems are binary, decimal and hexadecimal.

Create a program that displays ranges of integer values ​​(Listing 13.1). Compile the program and run it. Make sure that these values ​​correspond to those shown in Table 13.1.

In the source code of the program, find the line that sets the compilation mode:

($mode objfpc)($H+)

In this line, instead of the word objfpc write the word tp. That is, the final line should look like this:

($mode tp)($H+)

Launch the program. Look at the range of type values For example, data type. Draw conclusions.

Learn to think like a programmer, that is, logically. No one will chew on everything for you until retirement, as I do now. You have to get used to thinking for yourself. Otherwise, you will slip into the “monkey learning principle,” and then your chances of becoming a great programmer will be close to zero. To help you not slide into the “cramming” level, I will periodically leave gaps in your learning so that you try to figure out some things yourself.

It's much better if you figure it out yourself wrong decision, you will find the mistake yourself and correct it yourself, rather than always using other people’s correct solutions and stupidly copying them.

Pascal data types

Any data (constants, variables, function values ​​or expressions) in Turbo Pascal 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. The type also determines the format of the internal representation of data in the computer's memory.

There are the following data types in Turbo Pascal.

1) Simple types:

– real;

– symbolic;

– Boolean (logical);

– enumerated;

– limited (range).

2) Composite (structured) types:

– regular (arrays);

– combined (records);

– file;

– multiple;

– string;

– objects.

3) Reference types (typed and untyped pointers).

4) Procedural types.

Turbo Pascal provides a mechanism for creating new data types, thanks to which the total number of types used in the program can be as large as desired.

Integer type. Integer values ​​are the elements of a subset of integers. There are five integer types in Turbo Pascal. Their names, range of values, representation length in bytes are given in table. 6.

Table 6

Integer data types

Integer variables are described using the reserved words above:

i, j, k: integer;

Integer type data is stored exactly in memory. For example, variables of type integer occupy 2 bytes (16 bits) in memory, which are allocated as follows: 1 bit is allocated to store the sign of the number (0 if the number is positive, and 1 if the number is negative) and 15 bits to store the number in binary. Reckoning. The maximum decimal number that can be written as 15-bit binary is 32767.

When using procedures and functions with integer parameters, you should be guided by the “nesting” of types, i.e. wherever word is used, byte is allowed (but not vice versa), longint “includes” an integer, which, in turn, includes shortint.

For the integer type, five basic operations are defined, the result of which is also an integer: +, -, *, div, mod (addition, subtraction, multiplication, integer division and remainder of integer division). In arithmetic expressions, the operations *, div, mod have higher priority than the operations +, -. Examples of writing expressions:

The list of procedures and functions applicable to integer types is given in table. 7. The letters b, s, w, i, l denote expressions of type byte, shortint, word, integer, and longint, respectively; x is an expression of any of these types; identifiers vb, vs, vw, vi, vl, vx denote variables of the corresponding types. An optional parameter is indicated in square brackets.

Table 7

Standard procedures and functions applicable to entire 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(i) Byte Returns the high byte of the argument
Hi(i) Byte Same
Lo(i) Byte Returns the low byte of the argument
Lo(w) Byte Same
Odd(l) Byte Returns true if the argument is an odd number
Random (w) Same as parameter Returns a pseudo-random number uniformly distributed in the range 0...(w-1)
Sqr(x) x Returns the square of the argument
Swap(i) Integer
Swap (w) Word Swaps bytes in a word
Succ(x) Same as parameter Returns the next integer value, i.e. x+1
Pred(x) Same as parameter Returns the preceding integer value, i.e. x-1

When operating with integers, the type of the result will correspond to the type of the operand, and if the operands are of different integer types, the type of the operand that has the maximum range of values. Possible overflow of the result is not controlled, which can lead to errors in the program.

Real type. Values ​​of real types define an arbitrary number with some finite precision depending on the internal format of the real number. There are five real types in Turbo Pascal (Table 8).

Table 8

Real data types

Real variables are described using the reserved words above:

A real number in computer memory consists of 3 parts:

Sign digit of a number;

Exponential part;

Mantissa of the number.

The mantissa has a length from 23 (Single) to 63 (Extended) binary digits, which provides an accuracy of 7-8 for Single and 19-20 for Extended decimal digits. The decimal point (comma) is implied before the left (most significant) digit of the mantissa, but when operating on a number, its position is shifted to the left or right in accordance with the binary order of the number stored in the exponential part, therefore operations on real numbers are called floating point (comma) arithmetic .

Single, Double, and Extended types are accessed only under special compilation modes. To enable these modes, select the menu item Options, Compiler… and enable the option 8087/80287 in Group Numeric processing.

A special position in Turbo Pascal is occupied by the Comp type, which is treated as a real number without exponential and fractional parts. In fact, Comp is a large signed integer that stores 19...20 significant decimal digits. At the same time, in expressions, Comp is fully compatible with any other real types: all real operations are defined on it, it can be used as an argument to mathematical operations, etc.



Real numbers are specified in the decimal number system in one of two forms.

IN fixed point form the record consists of an integer and a fractional part, separated from each other by a dot, for example:

0.087 4.0 23.5 0.6

IN floating point form the entry contains the letter E, which means "multiply by ten to the power", and the power is an integer, for example:

7E3 6.9E-8 0.98E-02 45E+04

The following operations are defined on objects of real type: +, -, *, /.

The "*" and "/" operations have higher priority than the "+" and "-" operations.

If at least one operand is real, then the operations +, -, *, / lead to a real result. The division operation / leads to a real result even in the case of two integer operands, for example: 9/3 = 3.0.

To work with real data, standard mathematical functions presented in table can be used. 9. The result of these functions is also real.

Table 9

Mathematical functions that work with real data

Variables and constants of type REAL are prohibited from being used:

– in the functions pred(x), succ(x), ord(x);

– as array indexes;

– as labels in control transfer statements;

– as control variables (cycle parameters).

To convert a real number to an integer, you can use the following functions:

trunc(x) – integer part of x (x – real);

round(x) – rounding to the nearest integer (x is real).

Character type. Character variables are described using the reserved word char:

Values ​​of this type are selected from an ordered character set (ASCII set) consisting of 256 characters. Each character is assigned an integer from the range 0..255. For example, uppercase letters of the Latin alphabet A..Z have codes 65..90, and lowercase letters have codes 97..122.

The value of a character type variable is a single character surrounded by apostrophes, for example:

'F' '8' '*'

Character variables can be compared with each other, and the character codes are compared.

There are functions that establish a correspondence between a symbol and its code:

ord(c) – gives the number of the symbol c;

chr(i) – returns character number i.

These functions are inverse to each other.

Boolean type. Boolean variables are described using the reserved word boolean:

p1, p2: boolean;

Boolean type variables take two values: true(true), false(lie).

These values ​​are ordered as follows: false< true. false имеет порядковый номер 0, true имеет порядковый номер 1.

Boolean variables can either be assigned a value directly or use a Boolean expression. For example,

a, d, g, b: boolean;

Relation operations (<, <=, >, >=, =, <>), applied to integer, real, and symbolic variables, produce a logical result.

Logical operations on operands of the logical type also produce a logical result (operations are listed in descending order of priority) (for more details, see Tables 3 and 5):

not – negation (NO operation);

and – logical multiplication (AND operation);

or – logical addition (OR operation);

xor – exclusive OR.

The expression (not a) has the opposite meaning of a.

The expression (a and b) evaluates to true if only both a and b are true; otherwise, the value of this expression is false.

The expression (a or b) evaluates to false if only both a and b evaluate to false; otherwise, the result is true.

Enum type. A non-standard enumeration type is specified by an enumeration in the form of names of values ​​that a variable can take. Each value is named by some identifier and is located in a list surrounded by parentheses. General form of enumerated type description:

x = (w1, w2, …, wn);

where x is the name of the type, w1, w2,..., wn are the values ​​that a variable of type x can take.

These values ​​are ordered w1

The following standard functions apply to the argument w of an enumerated type:

succ(w), pred(w), ord(w).

color=(red, black, yellow, green)

ww=(left, up, right, down);

f: array of ww;

succ(d) = yellow;

Variables a and b are of type w. they can take one of three values, with on

Relational operations are applicable to values ​​of enumerated type: =,<>, <=, >=, <, >.

It is allowed to specify enumerated type constants directly in the section var without using partition type, For example

c,d: (red, black, yellow, green);

Range (limited) type. When defining a limited type, you specify the initial and final values ​​that a range type variable can take. The values ​​are separated by two dots.

The restricted type description is of the form

Here a is the name of the type, min, max are constants.

When specifying a restricted type, the following rules must be followed:

– both boundary constants min and max must be of the same type;

– a limited type is created from the data of a base type, which can be an integer, character or enumerated type. For example:

col = red.. yellow;

letter = ‘a’..’f’;

– Variables of a restricted type can be declared in the var section without referring to the type section:

– a restricted type inherits all the properties of the base type from which it is created;

– the min limit must always be less than the max limit.

Arrays. An array is a complex type that is a structure consisting of a fixed number of components of the same type. The component type is called the base type. All components of the array can be easily ordered and access to any of them can be provided by simply indicating its serial number. Description of the array in the section var has the form:

a: array of t2;

where a is the name of the array, array, of– service words (meaning “array of ...”), t1 – index type; t2 – component type (base type).

The number of indices determines the size of the array. Indexes can be integer (except longint), character, logical, enumeration, and range types. Subscripts are separated by commas and enclosed in square brackets. Array components can be of any type except file.

Example 1. Consider a one-dimensional array C, the values ​​of which are five real numbers:

4.6 6.23 12 -4.8 0.7

The description of this array is as follows:

c: array of real;

Based on a specific index value, you can select a specific array component (for example, C means the third element of the array C, i.e. the number 12).

Example 2. Consider a two-dimensional array B (matrix B), the value of which is a table of integers:

The description of this array is as follows:

b of integer;

Here b is the name of the array, the first index is the row number and takes values ​​from 1 to 2, the second is the column number and takes values ​​from 1 to 4. Based on specific index values, you can select a specific array component (for example, b means a table element located in first row and third column, i.e. number -4).

Indexes can be arbitrary expressions corresponding to the index type from the array description:

a: array of real;

a[(i+1)*2] := 24;

The set of operations on array elements is completely determined by the type of these elements.

String type. String type is a set of character strings of arbitrary length (from zero to a given number). Variables of string type are described using a function word string:

b: string ;

Peculiarities:

– the value of a string variable can be entered using the keyboard, assigned in an assignment operator, or read from a file. In this case, the length of the entered string can be any (less than the specified size, equal to the size or greater, in the latter case, extra characters are discarded); a:= ‘Results’;

– it is allowed to use the concatenation operation in the assignment operator, since strings can dynamically change their length: a:= a + ‘calculations’;

– the maximum length of a string variable is 255 characters, this length indication can be omitted:

a: string;

a1: string ;

Variables a and a1 are the same (equivalent description).

– memory for string type variables is allocated to the maximum, but only the part of the memory actually occupied by string characters at the moment is used. To describe a string variable of length n, n+1 bytes of memory are used: n bytes to store string characters, n+1 byte to store the current length.

– comparison operations are defined on values ​​of string types:< <= > >= = <>. A short string is always smaller than a long one. If the strings are the same length, then the character codes are compared.

– access to individual elements of a string is possible in the same way as access to array elements: a, a. The number of the line element is indicated in square brackets.

Procedures and functions oriented to working with strings.

concat (s1, s2,…)– string merging function, s1, s2,... - lines, the number of lines can be arbitrary. The result of the function is a string. If the resulting string is longer than 255 characters, the string is truncated to 255 characters.

copy(s, index, count)– function of extracting a string from a source string s length count characters, starting with character number index.

delete (s, index, count)– procedure for removing from string s a substring of length count characters, starting with character number index.

insert(s1, s2, index)– row insertion procedure s1 to line s2, starting with the character with the number index.

length(s)– function for determining the current string length, returns a number equal to the current string length.

pos(s1, s2)– search function in a string s2 substrings s1. returns the position number of the first character of a substring s1 in line s2(or 0 if this line does not exist).

val (st, x, code)– procedure for converting string s into an integer or real variable x. Parameter code contains 0 if the conversion was successful (and in x the result of the conversion is placed), or the line position number where the erroneous character is detected (in this case, the value x does not change).

Compatibility and Type Conversion. Turbo Pascal is a typed language. It is built on the basis of strict adherence to the type concept, according to which all operations used in the language are defined only on operands of compatible types.

Two types are considered compatible if:

– both of them are the same type;

– both are real;

- both are intact;

– one type is a range type of the second type;

– both are range types of the same base type;

– both are sets composed of elements of the same basic type;

– both are packed strings (defined with the preceding word packed) of the same maximum length;

– one is a string type, and the other is a string or character type;

– one type is any pointer, and the other is a pointer to its related object;

– both are procedural types with the same result type (for a function type), number of parameters, and type of mutually corresponding parameters.

Type compatibility is especially important in assignment operators. Let t1 be the type of the variable and t2 the type of the expression, that is, the assignment t1:=t2 is performed. This assignment is possible in the following cases:

– t1 and t2 are the same type, and this type does not refer to files, arrays of files, records containing file fields, or arrays of such records;

– t1 and t2 are compatible ordinal types, and the value of t2 lies within the range of possible values ​​of t1;

– t1 and t2 are real types, and the value of t2 lies in the range of possible values ​​of t1;

– t1 – real type and t2 – integer type;

– t1 – line and t2 – character;

– t1 – string and t2 – packed string;

– t1 and t2 – compatible packed strings;

– t1 and t2 are compatible sets and all members of t2 belong to the set of possible values ​​of t1;

– t1 and t2 are compatible pointers;

– t1 and t2 are compatible procedural types;

– t1 is an object and t2 is its descendant.

In a program, data of one type can be converted into data of another type. This conversion can be explicit or implicit.

Explicit type conversion calls special conversion functions whose arguments belong to one type and whose values ​​belong to another. An example is the already discussed functions ord, trunc, round, chr.

Implicit conversion is only possible in two cases:

– in expressions composed of real and integer variables, the latter are automatically converted to a real type, and the entire expression as a whole acquires a real type;

– the same memory area is alternately treated as containing data of one or another type (combining data of different types in memory).

In order for a machine to process any input data, it must “understand” what type the variables in which the values ​​are stored belong. In the absence of information about the data format, the computer will not be able to determine whether this or that operation is permissible in a particular case: for example, it is intuitively clear that it is impossible to raise a letter to a power or take the integral of a string. Thus, the user must determine what actions are allowed to be performed with each variable.

As in other high-level programming languages, variable types in Pascal are optimized to perform tasks of various types, have a different range of values ​​and length in bytes.

Subdivision of variable types

Variable types in Pascal are divided into simple and structured. Simple types include real and ordinal types. Structured ones include arrays, records, sets and files. Separately, pointers, objects and procedural types are distinguished.

Let's look at ordinal and real types. Ordinal types include 5 integer types, enumeration type and range type.

Ordinal types

There are 5 integer types, differing in byte length and range of values.

The length of Byte and ShortInt is 1 byte. The difference between them is that Byte stores only non-negative values, while ShortInt allows you to store negative ones (from -128 to +127). The Word and Integer types relate to each other in a similar way, with the only difference being that their size is 2 bytes.

Finally, LongInt allows you to store both negative and positive values ​​using 4 bytes - in the 16th power of numeric dimension on either side of zero. Various types of variables in Pascal contribute to the efficient solution of user tasks, since in each specific case both a small and a large range of values ​​may be required, and there may also be restrictions on the amount of memory allocated.

It is important to understand that zero takes up as much memory space as any other number. Thus, when forming a range of values, the minimum negative number in absolute value will be one greater than a positive one: for example, from -128 to +127.

Variables belonging to can take the value TRUE (true) or FALSE (false) and require 1 byte of memory.

The CHAR type allows you to store any of the many characters that exist in computer memory. At the same time, in symbolic variables in Pascal, only the code of the sign is actually stored, in accordance with which its graphic form is displayed.

Real types

Among the types of variables in Pascal, there are several numeric ones with the ability to write a fractional part. The differences between Single, Real, Double, and Extended types come down to the range of values ​​accepted, the number of significant digits after the decimal point, and the size in bytes.

According to the order presented above, a variable of each type will occupy 4, 6, 8 or 10 bytes.

Arrays

Structured data types are complex and allow you to combine a number of simple values ​​within a single variable. A prime example is an array, which can be defined as follows:

String=array of char;

Thus, we got a type called String, which allows us to define variables up to 100 characters long. The last line directly specifies a one-dimensional array Y of type String. Variables in Pascal are described by placing the identifier on the left side and the variable value on the right, after the equal sign.

The range of indices written in allows access to each specific element of the array:

In this case, we read the second element of the previously created array Y.

String variables in Pascal are also a special case of a one-dimensional array, because a string is a sequence of characters, i.e. elements of the char type.

Posts

A record consists of several fields filled with data of any type except file. In general, this type of variable is similar to a database element. For example, you can enter a person’s name and phone number:

type NTel = Record

The first line on the left indicates the name of the type, and on the right - the service word record. The second line contains a field with a name, the third - a phone number. The word “end” means that we have entered all the fields we wanted, and this completes the process of creating a record.

Finally, in the last line we set the variable One, which is of type NTel.

You can access both the record as a whole and its individual components, for example: one.NAME (i.e. variable_name. record_field_name).

Files

Pascal allows you to work with text, typed and untyped files, which are a structured sequence of components that have the same type.

When reading from or writing to a file, either the full address or its short form can be used:

‘C:\Folder\File2.txt’

The short form is used when the file is placed in the folder where the program that accesses it is stored. The full form can be used in any circumstance.

You can set a file type variable as follows:

f1: file of integer;

To work with files, various functions and procedures are used that associate a variable with a file on disk, open it for reading, writing and overwriting, closing it when finished, allowing you to create a new name and deleting the file from the computer.

Finally

Without the ability to use various types of variables in Pascal, the user will not be able to implement even the simplest task. In order for the program to execute the algorithm without errors, it is necessary to learn both function words and syntax, since the machine can “understand” commands only if they are written in the only correct way.

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

Description of Pascal's numeric data types (integers)

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. Thus, in Pascal 7.0 the following integer numeric data types are used:

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

  • Arithmetic:
    addition(+);
    subtraction(-);
    multiplication(*);
    remainder of division (mod);
    exponentiation;
    unary plus (+);
    unary minus (-).
  • Relation operations:
    equality relation (=);
    inequality relation (<>);
    ratio is less (<);
    ratio greater than (>);
    relation not less than (>=);
    attitude 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 power (maximum range of values). Possible overflow of the result is not controlled in any way (it is important!) , which may lead to errors.

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

Description of Pascal's numeric data types (reals)

The real numeric data type refers to a subset of real numbers that can be represented in the 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 numbers is called the mantissa, the second is the exponent. 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 – number order (r – integer); P – base of the number system. For example, for the decimal base, the representation 2E-1 (here E is the base of the decimal number system) will look like: 2*10 -1 =0.2, and the representation 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 type real, a variable of 4 bytes will be created in the computer memory. In this case, 3 bytes will be given for the mantissa, and one byte for the order.

The following operations can be performed on real numeric data types:

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

As you can see, Pascal is characterized by a rich range of real types, but access to numeric data types single, double Types in Free Pascal extended only possible under special compilation modes. These numeric data types are designed for hardware support for floating-point arithmetic, and to use them effectively, your PC must include a math coprocessor.

The numeric data type occupies a special position in Pascal. comp, which is treated as a real number without exponential and fractional parts. Actually, comp is a “large” signed integer that retains 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 to mathematical functions, etc.

About converting Pascal's numeric data types

In Pascal, implicit (automatic) conversions of numeric data types are almost impossible. 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 like this:

Var X: integer; Y: real;

That's 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 convert numeric data types automatically. The reverse conversion is automatically type real in type integer impossible in Pascal. Let's remember how many bytes are allocated for type variables integer Types in Free Pascal real: for integer data type integer 2 bytes of memory are allocated, and for real - 6 bytes. To convert real V integer There are two built-in functions: round(x) rounds 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 elements such as symbols, words, phrases, and sentences. A programming language also has similar elements: symbols, words, expressions (phrases), operators (sentences).

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

The Pascal 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 to;

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

Range of values;

(* *) or ( ) - comment.

Pascal program structure

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

Any Pascal program can consist of the following blocks (optional parts are marked with square brackets hereafter):

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

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

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

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

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

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

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

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

begin (beginning of the main body of the program)

<операторы>

end. (* end of the main body of the program *)

Later versions of Pascal language compilers no longer require specifying the program name, that is, the program line<имя_программы>; can be omitted. But this is only possible 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 header (program or unit).

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

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

Compiler directives

The line beginning with the symbols ($ is not a comment, but a compiler directive - a special command on which the process of compilation and execution of the program depends. We will consider directives in those sections to which they relate “by meaning”.

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

Identifiers

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

You can give your program objects any name, but you must make sure that they are different from the reserved words used by Pascal, because the compiler will still not accept variables with "foreign" names.

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 while the program is running.

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

All variables used in the program must be described in a special var section using the following template:

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

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

The Pascal language has a large set of different data types, but 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 running.

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

There are three types of constants in Pascal:

Unnamed constants (digits and numbers, symbols and strings, sets);

Named untyped constants;

Named typed constants.

Unnamed constants

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

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

Any sequence of numbers (perhaps preceded by a "-" or "+" sign, or broken up 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 symbols 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 related to the Boolean data type.

Examples of using unnamed constants include 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 a constant, then by its appearance the compiler itself will determine which (base) type it should be assigned to. Any constant already described can be used when declaring other constants, variables and data types. Here are some examples of describing 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 while the program is running.

Typed constants are described using the following template:

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

The examples below show how to do this:

const n: integer = -10;

b: boolean = true;

We will provide 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 to run a program be provided before it runs. To do this, in the variable description section (var), you need to list all the variables used in the program. In addition, you also need to tell the compiler how much memory each of these variables will occupy.

All this can be communicated to the program by simply indicating the type of the future variable. Having information about the type of a variable, the compiler “understands” how many bytes need to be allocated for it, what actions can be performed with it, and in what constructions it can participate.

For the convenience of programmers, Pascal has 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 himself), which are called constructed.

The division into basic and constructed data types in Pascal 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

indexed index

Constructed types

Listable

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

Typed pointer

Array

String string

record record

Procedural

Object

Interval (range)

Programmer Constructed Data Types

Ordinal data types

Among the basic data types, ordinal types stand out. 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, one can say exactly which of them is smaller and which is larger.

Standard routines that handle ordinal data types

The following functions and procedures are defined only for 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 function pred(x) returns the value preceding x (not applicable to the first element of the type).

3.The function succ(x) 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 k-e value preceding x (for arithmetic data types this is equivalent to the operator x:=x-k).

At first glance, it appears that the result of using 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 permissible range. The succ(x) function is not applicable to the maximum element of a type, but the inc(x) procedure will not produce 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 outside the 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 value comes the first value again.

Let us 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 give the following result:

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

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

dec(min_element)= max_element

Data types related to ordinal

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

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

pred(true)=false, succ(false)=true,

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

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

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

3. Let's summarize the integer data types in a table:

Data type

Number of bytes

Range

2147483648..2147483647

4. Enumerated data types are specified in the type section by explicitly listing 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 defined only by the boundaries of their range. For example:

type month = 1..12;

budni = mon..fri;

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

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

For example:

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

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

type int = integer;

You can shorten the program text 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

We will consider these data types (along with the operations defined for them) further over the course of 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 operators listed below (except for 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 values ​​of the boolean type. 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 basic types. Their results are also boolean values.

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

a div b - division of a by b completely (there is probably no need to remind you that division by 0 is prohibited, so in such cases the operation generates an error). 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 this way: integer is a minimal type of which both byte and shortint are subsets.

a mod b - taking the remainder when dividing a by b. The type of the result, as in the previous case, is determined by the types of the operands, and 0 is an illegal value for b. Unlike the mathematical operation mod, the result of which is always a non-negative number, the sign of the result of the "programmer" 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 - shifts the value of a by k bits to the right (this is equivalent to dividing the value of the variable a by 2k completely). 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 the corresponding logical operations.

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

Other operations

There are other operations specific to the values ​​of some of Pascal's standard data types. We will consider these operations in the appropriate sections:

#, in, +, *, : see lecture 5 “Symbols. Lines. Multitudes"

@, ^: see lecture 7 “Addresses and pointers”

Standard arithmetic functions

Arithmetic operations also include standard arithmetic functions. We provide a list of them with a brief description in the table.

Function

Description

Argument type

Result type

Absolute value (modulus) of a number

Arithmetic

Same as argument type

Arctangent (in radians)

Arithmetic

Real

Cosine (in radians)

Arithmetic

Real

Exponent (ex)

Arithmetic

Real

Taking the fractional part of a number

Arithmetic

Real

Taking the whole part of a number

Arithmetic

Real

Natural logarithm (base e)

Arithmetic

Real

Checking if a number is odd

Number meaning

Real

Round to the nearest integer

Arithmetic

Rounding down - to the nearest smaller integer

Arithmetic

Sine (in radians)

Arithmetic

Real

Squaring

Arithmetic

Real

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 call to the standard function;

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

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

Calculation order

If the expression contains parentheses, then the calculations are performed in the following order: the smaller the nesting depth of the parentheses, 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 priority. Several consecutive operations of the same priority are calculated in sequence from left to right.

Table 2.1. Priorities (for all) Pascal operations