Presentation "Pascal programming language. Language text editor." Pascal Programming Basics Download Pascal Computer Science presentation

Slide 1

PROGRAMMING LANGUAGE PASKAL Vladimir Bogdanov Free presentations http://prezentacija.biz/

Slide 3

The Pascal language was created by Niklaus Wirth in 1968-1969 after his participation in the committee for the development of the ALGOL-68 language standard. The language is named after the French mathematician, physicist, writer and philosopher Blaise Pascal, who created the world's first mechanical machine that adds two numbers. Wirth's first publication on the language dates back to 1970, introducing the language, the author indicated as the goal of its creation - building a small and efficient language that promotes a good programming style using structured programming and structured data. Wirth's subsequent work was aimed at creating a system programming language based on Pascal, while retaining the possibility of conducting a systematic, holistic course of training in professional programming on its basis. The result of this work is the language of Modula-2.

Slide 4

UCSD Pascal Main article: UCSD Pascal In 1978 at the University of California at San Diego, the UCSD p-System was developed, which included a port of the Wirth compiler from Pascal into a portable p-code, a source code editor, a file system, etc., and also implemented a significant number of extensions to the Pascal language, such as modules, variable-length character strings, translation directives, handling I / O errors, referring to files by name, and more. Subsequently, the main implementations of the Pascal language were based on this dialect.

Slide 5

Object Pascal] Main article: Object Pascal In 1986, Apple developed an object extension of the Pascal language, resulting in Object Pascal. It was developed by Larry Tesler's group, who consulted with Niklaus Wirth.

Slide 6

In 1983, the first version of Borland's Turbo Pascal integrated development environment appeared, based on the Pascal implementation of the same name. In 1989, an object extension of the language was added in Turbo Pascal version 5.5. The latest version (7.0) has been renamed Borland Pascal. Object facilities were borrowed from Apple's Object Pascal, and the language differences between Turbo Pascal 5.5's Object Pascal and Apple's Object Pascal are negligible. At almost the same time as Borland, Microsoft released its version of the object-oriented language, Pascal. And] This version of Pascal was not widely adopted. Further development of the Pascal implementation from Borland gave rise to the Object Pascal version from Borland, later, in the course of the development of the Delphi programming environment, which received the same name.

Slide 7

An important step in the development of the language is the emergence of free implementations of the Pascal l language and GNU Pascl, which not only absorbed the features of many other dialects of the language, but also provided extremely wide portability of programs written in it (for example, GNU Pascal supports more than 20 different platforms, under more than 10 different operating systems, Free Pascal provides special modes of compatibility with various common dialects of the language, such as Turbo Pascal (full compatibility), Delphi and others). Beginning with Delphi 2003, an implementation of the language for the Net platform was created, although developers continue to use earlier versions of Delphi. Little is known about commercial developments in Free Pascal, GNU Pascal, and TMT Pascal. In addition, the Southern Federal University has developed PascalABC.NET - the Pascal programming language, which includes most of the features of the Delphi language, as well as a number of its own extensions. It is based on the Microsoft.NT platform and contains almost all modern language facilities: classes, operation overloading, interfaces, exception handling, generic classes and routines, garbage collection, lambda expressions.

Slide 8

The peculiarities of the language are strict typing and the availability of structural (procedural) programming tools. Pascal was one of the first such languages. According to Wirth, the language should promote disciplined programming, therefore, along with strong typing, Pascal minimizes possible syntactic ambiguities, and the author tried to make the syntax intuitive even at the first acquaintance with the language.

Slide 9

Nevertheless, initially the language had a number of limitations: the impossibility of passing variable-length arrays to functions, the lack of normal means of working with dynamic memory, a limited I / O library, the lack of means for connecting functions written in other languages, the lack of separate compilation tools, etc. Detailed the analysis of the shortcomings of the Pascal language of that time was carried out by Brian Kernighan in the article "Why Pascal is not my favorite programming language" (this article was published in the early 1980s, when the Modula-2 language already existed, a descendant of Pascal, freed from most of its vices, and also the more developed dialects of Pascal). Some of Pascal's shortcomings were corrected in the 1982 ISO standard, in particular, open arrays appeared in the language, which made it possible to use the same procedures for processing one-dimensional arrays of different sizes.

Slide 10

However, many of the disadvantages of the language do not appear or even become advantages when teaching programming. In addition, compared to the main programming language in the academic environment of the 1970s (which was Fortran, which had much more significant flaws), Pascal represented a significant step forward. By the 1980s, Pascal became the basis for numerous educational programs, in some cases specialized teaching programming languages \u200b\u200bwere created on its basis, for example, in the early 1980s in the USSR, to teach schoolchildren the basics of computer science and computer technology, Andrei Ershov developed an algol-Pascal-like "Educational algorithmic language".

Slide 11

The most famous implementation of Pascal, which ensured the widespread and development of the language, is Turbo Pascal from Borland, which then grew into object Pascal for DOS (starting with version 5.5) and Windows and later in Delphi, in which significant extensions of the language were introduced. The Pascal dialects used in Turbo Pascal for DOS and Delphi for Windows have become popular due to the lack of other successful commercial implementations.

Slide 12

After the beginning of the use of Pascal in 1970 and the appearance of implementations that diverged not only in additions, but also in syntax, the question of standardizing the language was raised. The language standard was developed by Niklaus Wirth in 1974 in collaboration with Kathleen Jensen. Subsequently, an international standard from ISO and an American one from ANSI were adopted. At the moment, there are three fundamentally different standards: Unextended Pascal (original), Extended Pascal (extended), Object-Oriented Extensions to Pascal (object-oriented Pascal extension).

Slide 13

Slide 14

Syntax and Language Constructions Pascal, in its original form, is a purely procedural language and includes many algol-like structures and reserved word constructs like if, then, else, while, for, etc. However, Pascal is also contains a large number of possibilities for structuring information and abstractions that were absent in the original ALGOL-60, such as definition of types, records, pointers, enumeration, and sets. These constructions were partially inherited or inspired from the languages \u200b\u200bof Simula-67, Algol-64, created by Niklaus Wirth AlgolW (English) Russian. and suggested by Hoare. In modern dialects (Free Pascal), operations such as operator and function overloading are available.

Slide 15

program p; begin end. The program does nothing and contains an empty statement block. An example of a program that outputs the string "Hello, world!":

Slide 16

begin writeln ("Hello, World!"); (string output operator) end.

Slide 17

Slide 18

Slide 19

Slide 20

In Pascal, bitwise operations are allowed on integer types (byte, shortint, word, integer, longint and their ranges). Logical operations on bits: On the bits of two integer operands, you can perform the previously considered logical operations: not, and, or, xor. The difference between bitwise and logical operations is that bitwise (bitwise) operations are performed on the individual bits of the operands, and not on their (usually) decimal value. The concept of ordinal data types (ordinal) is highlighted, these include integer types (signed and unsigned), boolean (boolean), character (char), enumerated types and range types. Ordinal types are specified as an integer (code), which can be obtained using the ord function. All operations performed on ordinal types are performed with their codes.

Slide 21

Slide 22

For ordinal types, the operations inc, dec, succ, pred, ord, comparison operations (\u003d\u003e

Slide 23

Slide 24

Slide 25

In Pascal Jensen and Wirth, strings were represented as packed arrays of characters; therefore, they were of a fixed length and were usually padded to that length with spaces. Modern Pascal uses the built-in string type to work with strings, which supports concatenation (+) and comparison (\u003e \u003d

Slide 26

The type string [n] or simply string in dialects of the 1970-1990s language was defined as an array of characters array of char (n by default took the value 80 in UCSD Pascal and 255 in Turbo / Borland Pascal), the code of the null character in this representation serves to set the length of the string, so the string could have a maximum size of 255 characters. By default, Delphi and FreePascal use the AnsiString type as a String, memory for which is dynamically allocated and released by the compiler, and the maximum string size in current implementations is 2 gigabytes. In addition, in Delphi and Free Pascal, the WideString type can be used as a string, which uses a 16-bit representation of characters in the UCS-2 encoding, while there is no means of converting from single-byte strings to multibyte and back in the standard language library.

Slide 27

New types can be defined from existing ones: type (type declaration section) x \u003d Integer; y \u003d x;

Slide 28

Moreover, composite types can be constructed from primitive types: type (type declaration section) a \u003d Array of Integer; (array definition) b \u003d record (record definition) x: Integer; y: Char; end; c \u003d File of a; (file definition)

Slide 29

File types in Pascal are divided into typed, text and files without types. As shown in the above example, typed files in Pascal are sequences of the same type of elements. For each file, there is a buffer pointer variable denoted f ^. The get (read) and put (write) routines move the pointer to the next item. Reading is implemented so that read (f, x) is the same as get (f); x: \u003d f ^. Accordingly, the writing is implemented in such a way that write (f, x) is the same as f ^: \u003d x; put (f). Text files are defined as an extension of the file of char type and in addition to standard operations on typed files (reading, writing a character), they allow character input-output to a file of all data types similar to console input-output.

Slide 30

Files without types are declared as variables of type file. With them, you can perform byte untyped I / O operations for several blocks of bytes of a specified length through a buffer, for this purpose special procedures blockread and blockwrite (UCSD extension) are used.

Slide 31

Slide 32

Slide 33

Slide 34

Slide 35

Pointers Pascal supports the use of pointers (typed ^ type and untyped pointers): type a \u003d ^ b; b \u003d record x: Integer; y: Char; z: a; end; var pointer_to_b: a;

Slide 36

Here the variable pointer_to_b is a pointer to data type b, which is a record. The type of a typed pointer can be specified before the declaration of the type to which it refers. This is an exception to the rule that any thing must be declared before being used. The introduction of this exception made it possible to organize recursive definitions of data structures, including such as linear lists, stacks, and queues, including a pointer to the entry in the description of this entry (see also: null pointer - nil). A dereference operation is defined for a typed pointer (its syntax is the ^ pointer). To create a new record and assign the value 10 and the character A to the x and y fields in it, you need the following operators:

Slide 37

new (pointer_to_b); (memory allocation to a pointer) pointer_to_b ^ .x: \u003d 10; (dereferencing a pointer and accessing the record field) pointer_to_b ^ .y: \u003d "A"; pointer_to_b ^ .z: \u003d nil; ... dispose (pointer_to_b); (freeing memory from under the pointer)

Slide 38

For the purpose of referring to fields of records and objects, you can also use the with statement, as shown in the example: new (pointer_to_b); with pointer_to_b ^ do begin x: \u003d 10; y: \u003d "A"; z: \u003d nil end; ... dispose (pointer_to_b);

Slide 39

Procedural type In the original language of Pascal Jensen and Wirth, the procedural type was used only when describing a formal parameter. Already in TP there was a full-fledged procedural type. The type declaration contains the header of a procedure or function (without a name), which generally describes the interface of the subroutine. A value of this type contains a pointer to a subroutine with a header corresponding to that described in the type declaration. Using the variable identifier, the corresponding procedure or function can be called.

Slide 40

Pascal is a structured programming language, which means that a program consists of individual standard statements that are executed sequentially, ideally without the use of a GOTO command.

Slide 41

In statements while, for, if, case, a block can be used as an executable statement. Such a construction, which is an ordinary operator or block, is called a complex operator. In Turbo Pascal, to control the compilation process, there are directives that are placed in comments and allow you to switch the compiler's modes of operation - for example, enable and disable checking for I / O operations, overflows:

Slide 42

In Pascal, subroutines are divided into procedures and functions: Syntactically, procedures and functions consist of a header (containing the procedure or function keyword, a name followed by a description of the parameters passed in parentheses, a colon-separated return type for functions, and a semicolon for procedures ), the heading is followed by a body, followed by the symbol ;.

Slide 43

The body of a procedure, like a program, in turn, can contain descriptions of procedures and functions. Thus, procedures and functions can be nested as deeply into each other as desired, while the body of the program is the topmost in the chain. Moreover, the contents of the sections describing variables, types, constants, external body (procedure, function, program) located before the description of the procedure / function are available inside it. Also, in most dialects from the procedure, you can refer to the parameters of the external procedure. Following the procedure / function header instead of the body, the forward keyword can be placed, this is done if the procedure / function description is located in the program after its call, and is associated with the ability to compile the program in one pass, supported in Pascal. Procedures differ from functions in that functions return a value, but procedures do not.

Slide 44

Before the appearance of connected modules in their modern form, some Pascal implementations supported modularity due to the mechanism of including header files, similar to the #include mechanism in the C language: using a special directive, formatted as a pseudo-comment, for example, ($ INCLUDE "file"), content of the specified file was directly included in the program text in its original, text form. Thus, it was possible to divide the program code into many fragments for ease of editing, but before compilation, they were automatically combined into one program file, which was eventually processed by the compiler. This implementation of modularity is primitive and has many obvious disadvantages, so it was quickly replaced. Modern implementations of the Pascal language (starting with UCSD Pascal) support modules. Program modules can be of two types: the main program module, which, as usual, begins with the program keyword and the body of which contains the code that is run after the program is loaded into memory, and auxiliary modules containing types, constants, variables, procedures and functions intended for use in other modules, including the main module.

Slide 45

The general structure of the plug-in in Pascal is as follows: unit UnitName1; interface ... implementation ... begin (may be absent - used if initialization statements need to be placed) ... end.

Slide 46

Another option is also possible: unit UnitName2; interface ... implementation ... initialization ... finalization .... end.

Slide 47

Unlike the main program, a module file begins with the UNIT keyword, followed by the module name and a semicolon. Modern implementations generally require the name of a module to be the same as the name of the source file that contains the module. A module contains three sections: an interface section, an implementation section, and a module body.

Slide 48

The interface section comes first, starts with the INTERFACE keyword and ends at the point in the module where the implementation section or body begins. The interface section declares those objects (types, constants, variables, procedures and functions - headers are placed for them) that should be accessible from outside the module. In this case, partial declaration of types is allowed: they can be declared without specifying a structure, with only one name. When using this type in an external program, it is allowed to declare variables and parameters of this type, assign values, but it is impossible to get access to the details of its implementation. Procedures and functions in the interface section are declared as forwards - headers with parameters, but without a body. The composition of the interface section of the module is such that it is sufficient to generate code using this module. Variables declared in the interface section are global, that is, they exist in a single instance and are available in all parts of the program using this module.

Slide 49

The implementation section follows the interface section and begins with the IMPLEMENTATION keyword. It contains descriptions of procedures and functions declared in the interface section, as well as descriptions of types, constants, variables, procedures and functions that are required to implement interface procedures and functions. A description of a procedure or function declared in an interface section must have exactly the same title as in the declaration. The body can use other procedures and functions of this module, declared both in the interface part and in the implementation section. Variables declared in the implementation section are, in fact, global (that is, there is only one instance of each such variable for the entire program), but they are accessible only from the procedures and functions described in the implementation section of this module, as well as from its body. If there are abbreviated type declarations in the interface section, then these types must be fully described in the implementation section.

Slide 50

The body of the module begins with the BEGIN keyword at the top nesting level. The body contains program code that is executed once when the module is loaded. The body can be used for initialization, assigning initial values \u200b\u200bto module variables, allocating resources for its operation, and so on. The body of the module may be missing. In a number of Pascal implementations, for example, in Delphi, instead of the module body, two sections (also optional) can be used - INITIALIZATION and FINALIZATION. They are located at the end of the module, after the corresponding keyword. The first, the initialization section, contains the code that must be executed when the module is loaded, the second, the finalization section, contains the code that will be executed when the module is unloaded. The finalization section can perform actions inverse to the initialization - delete objects from memory, close files, release allocated resources. The module ends with the keyword END with a dot.

Slide 51

To use a module, the main program or another module must import this module, that is, contain a declaration about its use. This declaration is made using a module connection statement, which is the USES keyword followed by comma-separated names of the modules that you want to connect. The connection instruction must follow immediately after the program header, or after the INTERFACE keyword if the connection is made in a module.

Slide 52

Modules connected in the interface section can be used in the entire module - both in the implementation section and in the body. But the implementation section can have its own connection statement (it follows the IMPLEMENTATION keyword) containing the names of the plug-ins that are not in the interface section but are needed for the implementation section. One of the reasons for using a separate connection list for the implementation section is when two or more modules are using each other. To avoid circular references in the declarations of using such modules, at least one of them must include the other in the implementation section.

Slide 53

Any objects declared in the interface sections of modules can be used in the program where these modules are connected. The names of objects imported from plugins remain the same and can be used directly. If two or more connected modules have objects that are named the same, and the compiler cannot distinguish between them, then when trying to use such an object, a compilation error will be generated - an ambiguous name. In this case, the programmer must use the qualification of the name - specify the name in the "." Format.

Slide 54

Problems can arise if it becomes necessary to use two different modules of the same name in the program. If modules are available only in compiled form (that is, it is impossible to change their names), it turns out to be impossible to import them simultaneously. There is no standard solution to such a collision at the language level, but specific compilers may offer one or another way to work around it, in particular, means of assigning aliases to imported modules and directly specifying which module to take from which file.

Slide 55

Modules are designed to be compiled separately - the compiler does not have to compile imported modules in order to compile the module that uses them. However, in order to properly compile a module, the compiler must have access to the interface section of all modules it uses. There are two different, sometimes combined approaches to organizing such access. Modules are compiled into binary files of a special format (each compiler has its own), in which detailed information about the objects declared in the interface section is stored, they can also contain the language object created during the compilation of the module, but uses only the interface section of the module. If a library module is supplied in a compiled form (without full source texts), then a truncated file of the module's source code containing only the interface section is included with the binary file. This is enough for the compiler to correctly process calls from the using modules, and at the stage of building the program, the linker simply includes a binary file in the program.

Slide 56

Loading and unloading modules For normal operation of a module, you may need to perform some actions before using it: initialize variables, open necessary files, allocate memory or other resources. All this can be done in the body of the module, or in the initialization section. The reverse actions of initialization are done in the finalization section.

Slide 57

The order of initialization and finalization of units is indirectly determined by the order of declaration in the uses clause, but for statically compiled programs (where a unit is either compiled into one executable file with the main program, or is in a separate dynamic library, but loaded at the initial loading stage), the compiler always guarantees that that initialization will be performed before the first use of the module. Finalization is performed when the program exits, after the main module finishes, so that used modules are finalized later than those using them.

Slide 58

In the case of dynamic loading of modules, controlled by the programmer himself, the initializers are executed at load, that is, at the moment when the module load command returns control, its initializer has already been executed. The finalizer is executed after unloading, usually when a module unload command is executed. If this command is not called, dynamically loaded modules are finalized in the same way as all others - at the end of the program.

Slide 59

Object-oriented programming (OOP) is a technology for creating complex software that is based on representing a program as a collection of objects, each of which is an instance of a certain class, and the classes form a hierarchy with inheritance of properties.

Slide 60

The main advantage of OOP is a reduction in the number of inter-module calls and a decrease in the amount of information transferred between modules. This is achieved through a more complete localization of data and their integration with processing routines.

Slide 61

The main disadvantages in OOP are a slight decrease in performance due to a more complex organization of the software system, as well as, as a rule, a noticeable increase in the amount of binary code (especially when using standard class libraries in small programs) due to the fact that most modern compilers and linkers are not able to identify and remove all the code associated with unused classes, virtual methods and other elements of OOP.

Slide 62

In Object Pascal, classes are defined using the object type, similar to record, which, in addition to data fields, can contain headers of procedures and functions (they are called methods). The names of the described methods follow the class name separated by a dot.

Slide 63

The constructor and destructor are specified as normal procedures, but instead of the procedure identifier, the keywords constructor and destructor are specified. Accordingly, unlike C ++-like languages, they have a name different from the name of the class, there can be several destructors and they can have parameters (in practice this feature is rarely used, usually a class has a single destructor Destroy, which overrides the virtual destructor of the parent class ).

Slide 64

Single inheritance, class polymorphism, and the mechanism of virtual methods are supported (the word virtual after the class method header). There are also dynamic methods (in TP, they are described by adding an integer after the word virtual and are used mainly for processing messages; in Delphi and FreePascal, the word message is used for these purposes, and the word dynamic is used to create ordinary dynamic methods), which differ in less memory use and less call speed due to the absence of duplication of dynamic methods of ancestors in the descendant VMT (however, FreePascal does not distinguish between virtual and dynamic methods). Delphi, FPC implements operation overloading, abstract methods, private, protected, public, published directives (by default, class members are public):

Slide 65

In the Delphi dialect, classes can also be constructed using the word class (and mutual inheritance with object classes is not allowed) and interfaces are introduced - all methods are abstract and cannot contain data fields. All classes (created using class) inherit from TObject, all interfaces derive from IUnknown. Classes created with class can implement multiple interfaces.

Slide 66

In Delphi, interfaces were introduced to support Microsoft's COM technology. Classes (Class), unlike ordinary classes (Object), do not need to explicitly allocate / free memory, memory for them is dynamically allocated by the constructor named Create, called with the class name, and freed when the destructor named Destroy is called (they may have other names) ... The variable of such a class, unlike the object class, stores the address of an instance of the class in memory, the nil value is used to indicate an empty reference, therefore, a special free method is defined in TObject to free the object, which checks the reference for nil and calls the virtual destructor Destroy. The code using such classes will look like this:

Slide 67

Lesson topic: "Loops (repeat) in programs"

1) Review and consolidate the knowledge of drawing up linear, branching programs; 2) Learn to compose programs using a cyclic operator - FOR i: \u003d 1 TO n DO Begin operators (loop body) end; 3) Use operators in solving typical problems. The purpose of the lesson:

Insert the missing: Program Sql; Var A, B, C, D, XI, X2: ??? ; Begin Writeln ("Enter the coefficients of the quadratic equation"); Readln (???); D: \u003d B * B-4 * A * C; If D

Questions to the group: 1) What is the difference between programs with branching and linear ones? 2) What operators are used for selection in programs? 3) begin… .end - What is this? What are the rules of use in the program?

1) I / O Operators; 2) Operators of choice; 3) a: \u003d a + 3 - what will happen? 4) List data types; 5) Remove unnecessary AND, OR, END, NOT, IF; 6); - what does it mean? 7) How is the end of the program indicated? 8) List arithmetic operations. 9) What is 120 mod 65 \u003d? 10) Operators of the cycle.

Arrange accordingly: 1. Read 2. End 3. Begin 4. Integer 5.; 6. If .. Then 7.: \u003d 8. Enter 9. End 10. Integers 11. Assign 12. Next Action 13. Start 14. If .. Then

Is the result a less than 3? a: \u003d 7 b: \u003d - 10 a: \u003d a * (- 7) b: \u003d 159 a: \u003d b + a

Find 5 errors in the program: Program krug; VAR Pi, r, S: real; Pi: \u003d 3.14, WRITELN ('vvedite radiuc r \u003d'), READ (r); S \u003d Pi * r * r; WRITELN ('Ploshad kruga S \u003d', S) end

Program krug; VAR Pi, r, S: real; begin Pi: \u003d 3.14, WRITELN ('vvedite radiuc r \u003d'), READ (r); S: \u003d Pi * r * r; WRITELN ('Ploshad kruga S \u003d', S) end.

Problem number 1 Given an integer N, determine whether it is even or odd. 2, 4, 6,… are even, because are divided without remainder by 2 (N mod 2 \u003d 0) 1, 3, 7, ... - odd, since divided by 2 with remainder 1 (N mod 2 \u003d 1)

Algorithm Chislo Algorithm; variable N: integers; start Output (‘vvedite chislo’); Enter (N); IF N mod 2 \u003d 0 T O Output (N, '- chetnoe'); IF N mod 2 \u003d 1 T O Output (N, '- nechetnoe'); end.

Problem number 2 Given a two-digit integer number N (DE), where D - the number of tens, E - units. Determine whether the sum of the digits of this number will be 10. Example: for the 28th the sum S \u003d 2 + 8 \u003d 10 will be, and for the 27th S \u003d 2 + 7 \u003d 9 will not. Let's count tens: D \u003d N div 10 , and units: E \u003d N mod 10

Algorithm Chislo Algorithm; variable N, E, D, S: integers; start Output (‘vvedite chislo’); Enter (N); E: \u003d N mod 10; D: \u003d N div 10; S: \u003d E + D; IF S \u003d 10 T O Output ('summa \u003d 10') Otherwise ('summa10'); end.

Definition: Programs in which the same type of actions are repeated many times - cyclic programs (with repetition).

Problem: Given 100 natural numbers from 1 to 100 (1,2,3, ... 99,100) Calculate their sum and output to the variable S.

Algorithm sum; Var i, S: integers; Start S: \u003d 0; For i: \u003d 1 to 100 repeat Start S: \u003d S + i body End; loop Output (S) End.

Program summa; VAR i, S: integer; Begin S: \u003d 0; FOR i: \u003d 1 TO 100 DO begin S: \u003d S + i body end; loop WRITE (S) end.

Program summa; VAR i, S: integer; Begin S: \u003d 0; FOR i: \u003d 1 TO 100 DO begin S: \u003d S + i; body WRITE (‘S’, i, ’\u003d’, s) end; end.

The body of the cycle is the very action that needs to be repeated many times. The body of the loop is enclosed in operator brackets begin… .. end;

ALT + F9 - correcting errors CTRL + F9 - starting the program ALT + F5 - viewing the result

Task: 1) Display a column of the multiplication table of any integer N by numbers from 1 to 10. Example: N \u003d 5, then the column will be like this - 1 * 5 \u003d 5 2 * 5 \u003d 10 3 * 5 \u003d 15 i * N \u003d P , where i varies from …… .. 1… 10 10 * 5 \u003d 50

Homework: comment on the program for the problem "About the column of the multiplication table"

THANKS FOR ATTENTION!

Lesson topic: Programming language "PASKAL" Text editor of the language.

IT-teacher

GBOU School No. 293 named after A.T. Tvardovsky, Moscow

Bakhtinova Natalia Valerievna


Purpose of the lesson :

  • Form the first information about the Pascal language; Get skills to work in a text editor of the Pascal language .

Historical information about the Pascal language

  • The Pascal programming language got its name in honor of the great French mathematician and physicist Blaise Pascal, who in 1642. invented a calculating machine for arithmetic operations, the so-called "Pascal wheel". In late 1968, Professor Wirth and his collaborators at the Swiss Federal Institute of Technology in Zurich developed the first version of the Pascal language. Two years later - the first version of the compiler. In 1971 Wirth published a description of his language.

Blaise Pascal - French mathematician, mechanic, physicist, writer and philosopher


When creating Pascal Wirth, he pursued two goals:

  • first, to develop a language suitable for teaching programming as a systematic discipline;
  • second, the implementation of the language must be efficient and reliable.
  • One of the advantages of the Pascal language is that it fully embodied the idea of \u200b\u200bstructured programming, the essence of which is that with the help of several constructs, in principle, any algorithms can be expressed.

Niklaus Wirth (born February 15, 1934) is a Swiss scientist, one of the most famous theoreticians in the field of programming languages. Leading developer and creator of programming languages \u200b\u200bPascal, Modula-2, Oberon.


Launch of the Pascal language

To run the Pascal language, you need to load the PASCAL.EXE file located, as a rule, in the PASCAL directory.

For example: D: \\ PASCAL \\ PASCAL.EXE



  • We will write the program on a blue background.
  • Help lines are written on a gray background.
  • The top line contains dropdown menus: F isle, T text, IN execution, TO compilation, R modes, ABOUT tladka, H observation.
  • To go to the top menu, press F10. Pressing the alt key and the first letter of any of the words in the top menu brings up the window. (example alt + B)

  • Entering a program into a computer is typing text into a computer. Listed below are the most commonly used Turbo Pascal text editor commands.

  • PgUp - page up;
  • PgDn - one page down;
  • Home - to the beginning of the line;
  • End - to the end of the line;
  • Ctrl-PgUp - to the beginning of the text;
  • Ctrl-PgDn - to the end of the text.

  • Backspace (←) - erase the character to the left of the cursor;
  • Del - delete the character pointed to by the cursor (to the right of the cursor);
  • Ctrl-Y - erase the line where the cursor is located;
  • Enter - insert a new line, cut the old one;
  • Ctrl-Q L - restore the current line (effective if the cursor did not leave the changed line).

  • Ctrl-K B - mark the beginning of the block;
  • Ctrl-K K - mark the end of the block;
  • Ctrl-K Y - erase the block;
  • Ctrl-K C - copy block;
  • Ctrl-K V - move the block;
  • Ctrl-K W - write block to disk file;
  • Ctrl-K R - read a block from a disk file;
  • Ctrl-K P - print block;
  • Ctrl-K H - remove block selection.

  • In what year did the first version of the Pascal programming language appear?
  • What are the advantages of the Pascal language?
  • What keys are convenient to use to quickly move the cursor through the program from the upper left corner of the screen to the lower right corner? (what if the other way around?)
  • What do I need to do to copy a part of the program?
  • Is it possible to restore the changes made in the program text?

PASCAL INTRODUCTION TO THE PROGRAMMING LANGUAGE 2006 COURSE STRUCTURE interface and basic definitions; structure of the program; display of text information; data entry from the keyboard; connection and use of system modules; work with basic data types (integer, real, string, array, file); work with graphics; use of subroutines (procedures and functions); using modules. 2 PASCAL ENVIRONMENT INTERFACE Turbo Pascal 7.0 programming language is enclosed in a shell. It includes: a multi-window text editor; linker of programs; program debugger; help system; compiler. 3 PASCAL ENVIRONMENT 4 List of open files: Alt + 0 Quick access to open files: Alt +<№ окна> BASIC DEFINITIONS A reserved word is a special word used by a programming language to separate logical areas of a program. An operator is a language command that performs an action (checking a condition, organizing a loop, etc.). An identifier is a name freely chosen by the programmer for program elements. A data type is a characteristic of an identifier that determines the set of values \u200b\u200bthat it can take (integers or fractional numbers, character strings, logical expressions, etc.). 5 GENERAL PROGRAM STRUCTURE Program Program_name; Uses section of plugins; Label section of description of labels; Const section describing constants; Type section describing native data types; Var is the variable declaration section; Begin The main body of the program; End. Minimum code: 6 OUTPUT ON THE SCREEN To display information on the screen, the following operators are used: Write or Writeln. F9 - Compile + check Ctrl + F9 - Run F9 → Ctrl + F9 - avoid errors Displaying program execution results 7 DISPLAY ON SCREEN Result of using statements: WRITE "Empty" WRITELN statement adds a blank line WRITELN 8 EXERCISE Display the information on the screen as shown below Hello! Nice to see you! Call me computer. Material used: Output statements: Write, WriteLn "Empty" WriteLn statement; inserts an empty line. 9 CONNECTING ADDITIONAL MODULES Additional modules expand the capabilities of your programs by introducing additional operators. Modules are connected in the Uses section. Program My; Uses Module1, Module2; ________________________ ________________________ ________________________ ________________________ MODULE 1 Resource set 1 ... MODULE N Modules: System Own Resource set N Clear text screen Waiting for a key press A plug-in named CRT 10 OUTPUT TO ANY SCREEN LOCATION GotoXY (X, Y: Integer) Where X, Y - the coordinate of the familiarity on the screen. X can take values \u200b\u200bfrom 1 to 80, and Y from 1 to 25. For example: Program My_program; (Module connection) Uses Crt; Begin ClrScr; (Data Output) GotoXY (1, 1); write ("▒"); GotoXY (80, 1); write ("▒"); GotoXY (1, 25); write ("▒"); GotoXY (80, 25); write ("▒"); (Screen Delay) ReadKey; End. The program displays the symbol “▒” (code 177) in the corners of the screen. 11 OUTPUT IN COLOR TextColor (Color); Specifies the color of the characters. TextBackground (Color); Defines the color of the familiarity. Program MyProgram; Uses Crt; Begin TextColor (Red); TextBackGround (Blue); Write ("In the yard"); TextColor (White); Write ("grass,"); TextColor (Green); TextBackGround (Yellow); Write ("on the grass"); TextBackGround (Magenta); Write ("firewood. "); End. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Colors Black Blue Green Cyan Red Magenta Brown LightGray DarkGray LightBlue LightGreen LightCyan LightRed LightMagenta Yellow White 12 - black - blue - green - cyan - red - lilac - brown - light gray - dark gray - blue - light green - light cyan - pink - light lilac - yellow - white VALUES Data operations IDENTIFIERS The term identifier applies to constants, variables, functions, procedures, components and other user-defined objects. Allowed characters: Latin letters; numbers; underscore. Restrictions: must not start with a digit, but can start with an underscore .cannot contain multiple words .cannot match any of the keywords.IDs are not case sensitive ... Erroneous identifiers: Data My name 2Array Var ((((Russian characters are used) There is a space) Starts with a digit) Matches the keyword) 15 DATA TYPES A data type is a characteristic of an identifier that determines the set of values \u200b\u200bthat it can take (integer or fractional numbers, character strings, logical expressions, etc.). 16 INTEGRAL DATA TYPE 17 A finite set of possible values \u200b\u200btype byte shortint word integer longint range 0..255 -128..127 0..65535 -32768..32767 -2147483648..2147483647! Out of range results in an error! size DECLARATION OF VARIABLES A variable is an identifier capable of storing a value (number, string, etc.) and changing it during the program operation. Syntax: Var<имя переменной> : <тип переменной> ; Program Program_name; Uses section of plugins; Var is the variable declaration section; Begin The main body of the program; End. Reserved space in the computer memory for 3 variables 18 SETTING VALUES TO VARIABLES To set the value of a variable, you must use the assignment operator: \u003d Record syntax:<Переменная> := <Значение> ; A variable (integer) named A is filled with the value 3 19 OPERATIONS WITH INTEGER VARIABLES 20 Arithmetic operations: + - * / Standard operations: div | mod | sqr Cannot be used with integer types A variable named S is filled with the sum of the values \u200b\u200bstored in variables X and Y The value stored in a variable named S is displayed EXERCISE 21 1. Write a program that displays the result of the multiplication of numbers 15 and 20 2. Write a program that displays the value of the function f 2 x 3 y, for x \u003d 11, y \u003d 3 Material used: Variables are declared in the Var section The integer type is called Integer The syntax for assigning a value to a variable is:<Переменная> := <Значение> ; Each operator is followed by a sign; (except begin and last end) REAL DATA TYPE Set of values \u200b\u200b√ √ Ordinal type Real type One-way compatibility: Real Integer Integer Real! Out of range and non-compliance with the compatibility rules results in an error! 22 OPERATIONS ON REAL VARIABLES 23 Standard Operations: pi | Sqrt | Sin | Cos | Abs | Exp | Ln Round | Trunc (real → integer) For example (X, S - type Real): X: \u003d pi / 3; S: \u003d Sin (X) * 100; Write (Round (S)); In the variable named S, the ratio of the values \u200b\u200bstored in the variables X and Y is entered. The position of the number and the number of characters in the fractional part of the number E - denotes the power of the number. 5.6E-5 \u003d 5.6 · 10-5 LINE DATA TYPE 24 Strings are an ordered set of characters. Lines are enclosed in apostrophes. Strings are not compatible with integer and real types. Type Range String 255 characters (Basic operators for strings) + (concatenation) Length (S); (line length) For example: X: \u003d ‘Vasya’; Write (‘In your name’, Length (X), ‘letters’); S: \u003d X; X: \u003d S; EXERCISE Write a program that prints the result of dividing 12.89 and 0.22, displaying only three significant digits after the decimal point in the following format: divide the first number by the second \u003d result Write (X: 1: 3, 'razdelit na', y: 1 : 3, '\u003d' z: 1: 3) Material used: The string type is called String Strings are enclosed in opostraphs String concatenation occurs through the + sign In the display operator, different types are separated by a comma 25 KEYBOARD DATA 26 To enter information from the keyboard, you must use the input operator: Read or ReadLn. Syntax: Read (N1, N2, ... Nn); Where N1, N2,… Nn are variables (integer, real, string) In the variable X, the value entered from the keyboard is entered After entering the value, you must press the Enter key If there are several variables in the operator, they are entered through a space, or by pressing a key Enter EXERCISE 27 1. Write a "mini-calculator" program that calculates the sum of two numbers entered from the keyboard. 2. Write a program that asks for your name, and after you write your name displays a greeting. For example, if you entered the name Vanya, the program will display the phrase: Hello, Vanya !!! Used material: Input statements: Read, ReadLn OPERATORS CONDITIONAL STATEMENT 29 The conditional statement implements "branching", that is, it changes the order of execution of statements depending on the truth or falsity of a certain condition. Checking the condition NO Step 1 I'll go to the beach It's raining YES Step 2 I'll take an umbrella Step 3 I'll go to the cinema CHECKING THE CONDITIONS Comparison operations:\u003e - more< - меньше = - равно >\u003d - more or equal<= - меньше или равно <> - not equal to 30 Logical operations: Not And Or - Not -And - Or For example: If My height\u003e Petit's height, Then I am taller than Petit If (it is raining) Or (it is snowing), Then I will stay at home If Not ((it is raining ) AND (wind)), Then I'll go for a walk When using logical operations, conditions are enclosed in parentheses CONDITIONAL STATEMENT SYNOPSIS Short form: If<условие> then<оператор>; For example, if the variable X has a value less than 0, then the value 1 is written to the same variable: If X<0 Then X:= 1; Полная форма: If <условие> then<оператор_1> else<оператор_2> ; For example: If X\u003e 5 Then X: \u003d X - 1 Else X: \u003d X + 1; Only one statement can be used after Then and Else Before Else, sign; missing 31 EXERCISE 32 1. Write a program that receives an input in dollars and an amount in euros, and then displays on the screen in which currency the amount is greater (1 dollar \u003d 28 rubles, 1 euro \u003d 35 rubles.) 2. Write a program , which takes three numbers as input, and then displays the maximum of them. Material used: Forms of conditional statement: If<условие> Then<оператор>; If<условие> Then<оператор_1> Else<оператор_2> ; Before Else sign; not put Comparison operations:\u003e< = <> >= <= Логические операции: Not Or And ОПЕРАТОРНЫЕ СКОБКИ Если после слов Then или Else необходимо записать несколько операторов, то их заключают в операторные скобки (составной оператор). Операторные скобки начинаются словом Begin, а заканчиваются словом End; Например: If Z > 0 Then Begin X: \u003d 1; Y: \u003d -1; WriteLn (‘Information received’); End Else WriteLn ('Error'); 33 SELECT STATE CASE The select statement is used to replace constructs from nested conditional statements. Case syntax<порядковая_переменная> of<значение_1> : <оператор_1> ; <значение_2> : <оператор_2> ; ……… <значение_N> : <оператор_N> Else<оператор_N+1> ; End; Operator brackets can be used in the select statement Optional line 34 SELECTOR CASE Case Student height of 16..30: You are a primary school student; 31,32,33: You are in grade 5-6; 34..50: You are a high school student. A comma is used to list values, a colon is used to select a range. Else You are clearly not a student; End; Case x of -128 ..- 1: writeln (‘Negative’); 0: writeln (‘Zero’); 1..127: writeln (‘Positive’) Else WriteLn (‘Out of range’); End; EXERCISE Write a program that receives a number and displays the corresponding day of the week. For example, if you entered the number 2, the program should print ‘Tuesday’. If the number goes beyond 1..7, then a message should be displayed that there is no such day. Material used: Selection statement: Case<порядковая_переменная> of<значение_1> : <оператор_1> ; ……… <значение_N> : <оператор_N> ; Else<оператор_N+1> ; End; 36 CYCLES 37 Cyclic algorithms are those algorithms in which some operators are executed multiple times with the same modified data (for example, the procedure for multiplying numbers through their multiple addition). In Pascal, there are three loop statements: For (a loop with a parameter or for a given number of repetitions) While (a WHILE loop) Repeat (a TO loop) If the number of repetitions is known, it is better to use a loop operator with a parameter. CYCLE WITH PARAMETER 38 A cycle for a given number of repetitions with an increasing or decreasing value of the parameter For (pairs): \u003d (start_zn) To (end_zn) Do (operator); Loop body Remarks The parameter is an integer type; You can use operator brackets in a loop; You cannot change the loop parameter in the body of the loop; The loop parameter is increased by one; Start value\u003e End value, otherwise the body of the loop is ignored; To decrease the parameter, in place of To, use DownTo. CYCLE WITH PARAMETER 39 Write a program that asks for integers (a, b), with a := <нач_зн> To<кон_зн> Do<оператор> ; The parameter is an integer type (usually Integer); You can use operator brackets in a loop; The Loop Parameter is incremented by one 40 WHILE CYCLE The While Loop first checks for a condition, and only if it truly executes the body of the loop. While (condition) do (operator); In the body of the code written below, the loop will never be executed: x: \u003d 1; While x\u003e 1 do x: \u003d x-1; You can get an endless loop. For example: x: \u003d 1 While x\u003e 0 do x: \u003d x + 1; 41 WHILE CYCLE A program that displays the sum of the numbers a to b. While not keypressed do begin Delay (2000); End; The cycle works until the changing variable f becomes greater than the value b 42 EXERCISE 43 1. The cosmonauts decided to plant birches on the moon, and every year to double the number of birches, in the first year they planted 3 birches. Print on the screen in how many years the number of birches will exceed 10,000. 2. Write a program that determines the maximum of the entered numbers from the keyboard (entering numbers ends with the number 0). Below is the recommended screen layout: Enter the numbers. Enter 0. 89 15 0 Maximum number 89 to complete the entry. Material Used: While Loop Statement: While<условие> do<оператор> ; The While Loop first checks for a condition, and only if it truly executes the main body of the loop. REPEAT CYCLE 44 The Repeat loop first executes the loop body, and only then checks the Repeat condition (loop-body) Until (condition); There is no need to use a compound operator in the Repeat loop, because this construction provides for the execution of not one, but several operators enclosed between the words Repeat and Until. REPEAT CYCLE A program that displays the sum of numbers from a to b. The loop runs until the changing variable f becomes greater than the value b 45 COMPARING LOOPS For While Repeat 46 The choice of the loop model depends only on the convenience of its use in a particular situation. We can almost always use another instead of one type of cycle EXERCISE Calculate the value of the function y x 3 x 2 16 x 43 for x varying in the range from -4 to 4, inclusive, with a step of 0.5. Material used: Repeat loop statement: Repeat<тело_цикла> Until<условие> The Repeat loop first executes the body of the loop, and only then checks the condition 47 INTERRUPTION OF CYCLES 48 For flexible control of cyclic operators, the following procedures are used: Break - exit from the loop; Continue - completion of the next loop pass; Examples: Find the minimum number i for which the sum of numbers from 1 to i is greater than 100. As soon as s (the sum of numbers from 1 to i) becomes greater than 100, the break statement is triggered and the loop is exited. s: \u003d 0; for I: \u003d 1 to 100 do begin if s\u003e 100 then break; s: \u003d s + i; end; Writeln (‘the minimum number i, such that (1 + 2 + .. + i)\u003e 100 is’, i); 10 numbers are entered from the keyboard and only positive sums are counted in the loop. If the number is negative, then the continue statement is executed, which begins the next pass through the loop. s: \u003d 0; for I: \u003d 1 to 10 do begin Readln (k); if k<0 then Сontinue; s:= s + k; end; Writeln (‘Сумма положительных чисел равна ’,s); МАССИВЫ МАССИВЫ 50 Простые типы: одна переменная – одно значение Структурированные типы: одна переменная – несколько значений Массив – это фиксированное количество значений одного типа. Доступ к конкретному значению осуществляется через индекс. Переменная массива Структура массива: A= Доступ к массиву: 0 1 2 3 Индекс 9 7 0 0 Значения <Имя массива> [ <Индекс> ] A: \u003d 7; ARRAYS An array is declared in the Var section: (Name): Array [(start_zn) .. (end_zn)] of (type); Examples of declaring arrays: Var A: Array of String; B: Array of Real; С: Array of Integer; Examples of filling arrays with values: A: \u003d 'Vasya'; A: \u003d ‘Petya’; A: \u003d ‘Masha’; A: \u003d ‘Olesya’; Write (A); For f: \u003d 1 to 10 do C [f]: \u003d f * 2; For f: \u003d 1 to 10 do WriteLn (C [f]); EXERCISE 52 Write a program that asks the user for 7 integers and stores them in an array. The array contains the maximum element and is displayed on the screen. For example: Enter 1 number: 4 Enter 2 number: 8 Enter 3 number: 9 Enter 4 number: 2 Enter 5 number: 4 Enter 6 number: 5 Enter 7 number: 0 Maximum number: 9 Material used: Array declarations:<Имя> : Array [<нач_зн> … <кон_зн> ] of<тип> ; Array access:<Имя массива> [ <Индекс> ] RANDOM NUMBER GENERATOR (RNG) To generate random numbers in the program, use the following operators: Randomize - RNG initialization. It is declared only at the very beginning of the program; Random - generates a random number from 0 to 1 (real type); Random (N) - generates a random number from 0 to N-1 (integer type); 53 MULTI-DIMENSIONAL ARRAYS 54 List of intervals for each dimension of the array (Name): Array [(start_zn) .. (end_zn), (start_zn) .. (end_zn), (etc.)] of (type); An example of declaring a two-dimensional array (matrix, table) with 4 rows and 6 columns: Var A: Array of Integer; An example of filling an array: For i: \u003d 1 to 4 do For j: \u003d 1 to 6 do A: \u003d i + j; Ai, j 2 3 4 5 3 4 5 6 4 5 6 7 5 6 7 8 6 7 8 9 7 8 9 10 EXERCISE Write a program that fills a two-dimensional array with random numbers from -10 to 20 and displays the sums of the elements located on the diagonal of the table ... Material used: RNG initialization: Randomize Random number from 0 to N-1: Random (N) 55 WORKING WITH FILES WORKING WITH FILES 57 File: Start of file Index) [email protected]$ ku⌂ | "Hd9v * 9 (L * M \u003d BYGRMxduV █ 8e * BOtCDrTVzHGJ1aBD\u003e @ B \\ (r8sE) █: wcJvAmRa" v / .Wai; $ `SWI \u003d y2] suB █? Hq\u003e vF (LmBcV ^ .6b] o (QkВ8 █ cu<6`8Z":M^1;:8ANwak;,b2-4…u5 █ 2]suB?Hq>vF (LmBcAdz4wcP] o (QkВ █ 8c8df] e "v, su\u003e +), VAEFБjFV, W $ Q- █ y0G1GjN $ -eБ | sqZ0`QnВ% \\ БD% y █ █ █ - line terminator █ - terminator file Variable Create, read, write, close WORKING WITH FILES The sequence of actions when working with files: 1. Declaration of a file variable (FP); 2. Association of the FP with a file; 3. Opening a file for reading / writing; 4. Operations with file; 5. Closing the file (the connection between the file and the FP is also broken); 1. Declaration of the FP<Имя> : File of<тип> ; <Имя> : Text; Var f: Text; h: File of Integer; 2. Association of FP with the Assign (<ФП>, <имя файла>); Assign (f, ‘c: \\ my \\ Data.ghm’) 58 WORKING WITH FILES 3. Opening a file for reading / writing Reset (<ФП>); - opens file for reading Rewrite (<ФП>); - opens file for writing 4. Operations with file Read (<ФП>, <П1> , <П2> , ...); - reads into variables<П1>, <П2> etc. one element at a time from the position of the pointer. Write (<ФП> , <П1> , <П2> , ...); - writes the values \u200b\u200bof variables to the file<П1>, <П2> etc. one element at a time from the position of the pointer. EoLn (<ФП>); - Returns True if the end of the string is reached. EoF (<ФП>); - Returns True if end of file is reached. 5. Closing the file Close (<ФП>); 59 WORKING WITH FILES Simplify the program if you know that the matrix is \u200b\u200b5x5 (use the For loop) 60 EXERCISE 61 Write the program "DOM-3". The first file contains the names of the participants in the nominative case. In the second, the same names, but in the accusative. In the third - a list of expressions of feelings or some kind of action (loves, dislikes, kisses, wants to bite, adores, respects, hates, wants to see, hugs). The program should randomly take information from these files and create a new one according to the following principle:<имя в им. пад> <чувство/действие> <имя в вин. пад> Olga loves Sergey Oleg wants to see Roman Katya respects Nastya Etc. Material used: Operator names: Assign, Rewrite, Reset, Write, Read, Close. GRAPHICS GRAPHICS To work with graphics in Pascal, you need two files - the graph.tpu module and the egavga.bgi graphics adapter driver. The first is in the \\ UNITS directory and the second is in \\ BGI. ! Egavga.bgi driver. Required when running an exe file! To draw, you need to: 1. connect the GRAPH module (in the Uses section); 2. initialize graphics (InitGraph); 3. draw something; 4. close graphic mode (CloseGraph) 63 GRAPHICS Initialization of graphic mode Line drawing. The pen moves from point (0,0) to point (639, 479). PROGRAM Primer_1; Uses Graph, crt; Var Gd, Gm: Integer; BEGIN Gd: \u003d 0; InitGraph (Gd, Gm, 'd: \\ BP \\ bgi "); Line (0,0,639,479); ReadKey; CloseGraph; END. 639 pixels Coordinate system 479 pixels 64 Closing the graphics mode EXERCISE 65 1. Draw a rectangular in the center of the screen triangle 2. Draw in the center of the screen a rectangle with sides two times smaller than the corresponding sides of the screen Material used: Graphics module: Graph Graphics initialization: InitGraph Closing graphics mode: CloseGraph; GRAPHICS + COLOR SetColor (Color: word); Sets the pen color GetColor: word; Returns the pen color SetBkColor (color: word); Sets the background color GetBkColor: word; Returns the background color Colors Black Blue Green Cyan Red Magenta Brown LightGray DarkGray LightBlue LightGreen LightCyan LightRed LightMagenta Yellow White 66 - black - blue - green - cyan - red - lilac - brown - light gray - dark gray - blue - light green - light cyan - pink - light lilac - yellow - white GRAPHIC PRIMITIVES Line (x, y); Draws a line from the current pen coordinate to (x, y) coordinates. MoveTo (x, y); Sets the pen to coordinates (x, y). PutPixel (x, y, Color); Draws a point at coordinates (x, y) with Color. GetPixel (x, y): word; Returns the color of the point with coordinates (x, y). Rectangle (x1, y1, x2, y2); Draws the outline of a rectangle. Circle (x, y, r); Draws a circle with center (x, y) and radius r. SetLineStyle (Ln, 0, T) Changes the parameters of the contours. Ln - line style (0..3): 67 x1, y1 T - line thickness: 1 \u003d normal; 3 \u003d thick. FillEllipse (x, y, Xr, Yr); Draws a filled ellipse centered at (x, y) with radii Xr and Yr. SetFillStyle (Type, Color); Sets the type (0..11) and hatch color of closed shapes to ClearDevice; Clears the graphic screen by painting it in the current background color x2, y2 GRAPHIC PRIMITIVES 68 EXERCISE 69 1. Write a program that draws a house on the monitor screen; 2. Write a program that draws a starry sky with stars of random radius (from 1 to 5 pixels) and random arrangement on the monitor screen. The color is also random (white, light gray, dark gray); Used material: SetColor (Color: word); - Sets the drawing color SetBkColor (color: word); - Sets the current background color. Line (x, y); - Draws a line from the current pen coordinate to the (x, y) coordinates. MoveTo (x, y); - Sets the pen to coordinates (x, y). PutPixel (x, y, Color); - Draws a point with coordinates (x, y) with Color. Rectangle (x1, y1, x2, y2); - Constructs a rectangle outline from lines of the current color. Circle (x, y, r); - Draws a circle with center at (x, y) and radius r. FillEllipse (x, y, Xr, Yr); - Draws a filled ellipse centered at (x, y) and radii Xr and Yr. GRAPHICS + ANIMATION Pause in mS. 70 SUBPROGRAMS SUBPROGRAMS Subroutines allow you to select a repetitive part of the code in separate fragments and insert them into the necessary places in the program. A function, unlike a procedure, returns the result of the call. Procedures Functions Subroutines: written between the keywords Begin End; identified by names, which are written according to the rules for specifying identifiers; can have input and output parameters; completely repeat the structure of the main program. 72 Program My; Subroutine 1 [Subroutine code 1] Subroutine 2 [Subroutine code 2] Begin Subroutine 2 Subroutine 1 An example of system subroutines: Write (“Ok”); ClrScr; Length (S); Random; // // // // procedure with one parameter procedure without parameters function with one parameters function without parameters Subroutine 2 End. SUBPROGRAMS (PPR) Nesting of subroutines Program Subroutine 1 Subroutine 3 Subroutine 4 Subroutine 2 73 Accessibility area of \u200b\u200bvariables Variables described in some PPR are known within its body, INCLUDING all nested PPR (the variable described in PPR1 will be available in PPR3,4) ... The names of the variables described in the PMD can coincide with the names of variables from other PMDs (in each of the PMD the same variable can be declared). The name of the variable described in the PPR screens the variables of the same name from the PPR enclosing the given one (if the same variables are declared in PPR1 and PPR3, then in each PPR these variables will be unique). Program variables are called global, and subroutine variables are called local. PROCEDURES WITHOUT PARAMETERS Syntax: Procedure (procedure name); (Section of variables, constants, types, labels, modules) Begin (Procedure body); End; An example of using a procedure without parameters: 74 PROCEDURES WITHOUT PARAMETERS An example of escaping variables of the same name: Program My_program; Uses Crt; Var A: String; // Description of the procedure Procedure My_Procedure; Var A: String; Begin A: \u003d "Subroutine"; Writeln (A); End; Begin A: \u003d "Body"; Writeln (A); My_Procedure; Writeln (A); End. // Procedure call 75 PROCEDURES WITH PARAMETERS 76 In order to make the subroutines more universal, special mechanisms of data exchange between the program and its subroutines are used. System procedures with parameters: SetColor (Red); (Procedure with Rectangle (0, 0, 639, 479); (Procedure with InitGraph (Gd, Gm, 'd: \\ BP \\ bgi "); (Procedure with (one parameter) several parameters) several different types)) Write syntax procedures with parameters Procedure (Name) ((Scope of input variables) Var (Scope of output variables (for each variable its own Var))); Structure of areas: Variable_1, Variable_2,…: Type; ........... ............. Variable_N-1, Variable_N,…: Type; Any of the areas can be absent PROCEDURES WITH PARAMETERS Using input parameters Procedure for drawing a rectangle bordering the screen of a specified color Without parameters With parameters Procedure Cir; Begin SetColor (i); SetBkColor (b); Rectangle (0, 0, 639, 479); End; Procedure Cir (i, b: Integer); Begin SetColor (i); SetBkColor (b); Rectangle (0, 0, 639, 479); End; Procedure call in the program: Procedure call in the program: i: \u003d 6; b: \u003d 12; Cir; Cir (6, 12); 77 PROCEDURES WITH PARAMETERS Using output parameters Procedure Ra converting an angle from a degree to a radian. PROGRAM EX_26_3; VAR x, a: real; PROCEDURE Rad (alfa: real; var betta: real); (output variable) BEGIN Betta: \u003d pi * alfa / 180; END; BEGIN Write ("Enter the angle in degrees:"); Readln (x); Rad (x, a); (Procedure call) Writeln ("It is equal to the angle in radians \u003d", a: 6: 4); END. EXERCISE 79 1. Write a procedure that draws a triangle in the following format: Triangle (x1, y1, x2, y2, x3, y3, Color) 2. Write a procedure for calculating the area of \u200b\u200ba rectangle in the following format: SRect (a, b, S) where, S is the output parameter of the procedure. Material used: Procedure (Name) ((Input variable scope) Var (Output variable scope)); Structure of areas: Var_1, Var_2,…: Type; ........................ Variable_N-1, Variable_N,…: Type; FUNCTIONS 80 The syntax for writing a function Function ((Input variable area) Var (Output variable area)): (Type); Formatting the procedure Formatting the function Procedure S (a, b: real; var s: real); Begin s: \u003d a + b; End; Function Sum (a, b: real): real; Begin Sum: \u003d a + b; End; Procedure call Function call S (10, 20, A); Write (A); A: \u003d S (10, 20); WriteLN (A); WriteLN (S (20, 30)); It is advisable to design some subroutine as a function only if some result of its work is expected. If a subroutine is focused only on performing a certain sequence of actions (displaying, drawing, etc.), it is better to design it as a procedure. EXERCISE Write a function to calculate the area of \u200b\u200ba rectangle in the following format: SRect (a, b) Material used: Function (Name) ((Input variable region) Var (Output variable region)): (Type); Structure of areas: Variable_1, Variable_2,…: Type; ........................ Variable_N-1, Variable_N,…: Type; 81 UNITS UNITS 83 UNIT is an independent program unit, the resources (procedures and functions) of which can be used by other programs. Program My1; Uses Module1, Module2; __________________________ __________________________ __________________________ __________________ MODULE 1 Resource set 1… Program My2; Uses Module1, Module2; __________________________ __________________________ __________________________ __________________ MODULE N Set of resources N Modules are connected to the program through the USES MODULES section. STRUCTURE 84 The module consists of the following parts: 1. Module header. 2. The interface part. (descriptions of visible objects) 3. Implementation part. (descriptions of hidden objects) 4. Initialization part (optional). Unit (Unit name); Interface (Section of global variables, constants, types) (modules) (List of headers of procedures and functions) Implementation (Section of local variables, constants, types) (Implementation of procedures and functions) Begin (Part of initialization) End. ! The module header name must match the module file name! MODULES Example of a module: Unit My_Unit; Interface Var ms: Array of Real; (Global array) Function Cub (x: integer): Integer; (Cub function \u003d x ^ 3) Function ext4 (x: integer): Integer; (Function ext4 \u003d x ^ 4) Implementation Function Cub (x: integer): Integer; (Implementation of the Cub function) Begin Cub: \u003d x * x * x; End; Function Ext4 (x: integer): Integer; (Implementation of ext4 function) Begin Ext4: \u003d x * x * x * x; End; End. 85 EXERCISE 86 Write a module with one function and one procedure: (Function calculation X1 \u003d 1 / x) X1 (a: real): real; (The procedure for printing the word S on the screen, in position X, Y WriteXY (S: String; X, Y: Iteger); Used material (module structure): Unit (Module name); Interface (Section of global variables, constants, types) ( modules) (List of procedure and function headers) Implementation (Section of local variables, constants, types) (Implementation of procedures and functions) Begin (Initialization part) End.)

Did you like the article? To share with friends: