When solving new problems, you can try to use previously written programs. An algorithm previously developed and used entirely as part of other algorithms is called auxiliary. The use of auxiliary algorithms allows you to break the problem into parts and structure it.

The entire program can be divided into two parts: main and auxiliary. In the main part, the simplest information processing is carried out, access to various auxiliary modules (subroutines) is organized.

An auxiliary algorithm can also call other auxiliary algorithms; the length of such a chain of calls is theoretically unlimited. Here and below, the following pairs of words are used as synonyms: algorithm and program, auxiliary algorithm and subroutine, command and operator, program and module. Auxiliary and main algorithms are not in themselves, but in relation to each other.

When using auxiliary algorithms, it is necessary to consider the way in which the values ​​of the source data are transmitted to them and the result obtained from them. The arguments of the auxiliary algorithm are variables in which the initial data must be placed to solve the corresponding subtask. The results of the auxiliary algorithm are also variables that contain the results of solving these subproblems, and the result can also be a specific action that the computer performs under the influence of the subroutine.

Subroutines can be of two types: a subroutine without parameters and a subroutine with parameters. A subroutine can be called from anywhere in the main program or another subroutine as many times as desired.

When working with subroutines, the concepts of formal and actual parameters are important. Formal parameters are input identifiers for a routine. If formal parameters receive specific values, then they are called actual. Formal parameters can receive specific values ​​only in the program where the given subroutine module is accessed. The type and order of writing actual parameters must be the same as formal parameters. Otherwise, the result of the program will be unpredictable. It follows from this that actual parameters are used when accessing a subroutine from the main one, and formal parameters are used only in the module itself.

A subroutine with parameters is used to record repeatedly repeated actions with different initial data. Subroutines with parameters can be divided into two types: subroutines-functions and simply subroutines with parameters (they are called procedures).

When composing subroutines with parameters, the following rules must be observed:

1) each subroutine has its own name and list of formal parameters;

2) the procedure from the main program is called by a call command, which in form is no different from calling an executor command. The result is assigned to one or more variables that are in the list of formal parameters. But the result can, of course, be not only the values ​​of the variables, but some action performed by the computer.

Example 1. We use the algorithm for finding the greatest common divisor of two natural numbers as an auxiliary one in solving the problem: create a program for subtracting fractions (a, b, c, d are natural numbers). Present the result as an ordinary irreducible fraction.

Subroutine.

1) Enter natural numbers M, N.

2) If M=N, go to step 5, otherwise go to the next point.

3) If M>N, then M:=M-N, otherwise N:=N-M.

4) Go to step 2.

5) Pass the value of M to the main program.

6) End of the subroutine.

Main program.

1) Enter the values ​​A, B, C, D.

2) E:=A*D - B*C.

4) If E=0, output the value of E and go to step 9, otherwise go to the next step.

5) M:=|E|, N:=F, go to the GCD calculation subroutine.

7) Divide E and F completely by G.

8) Print the values ​​of E and F.

9) End of the program.

Var A, B, C, D, G, E, F: Integer;

Procedure Nod(M, N: Integer; Var K: Integer);

While M<>N Do

If M >

Write("Enter the numerators and denominators of the fractions:");

ReadLn(A, B, C, D);

E:= A * D - B * C;

If E = 0 Then WriteLn(E)

Nod(Abs(E), F, G);

WriteLn("Answer: ", E, "/", F)

As can be seen from the example, the declaration and body of the subroutines are located in the descriptions section. The subroutine header contains a list of formal parameters indicating their type, which can be divided into input and output parameters (they are preceded by the service Var). When a procedure is called, its name and a list of actual parameters are specified. Formal and actual parameters must correspond in quantity and type.

The procedure is called as follows:

<Идентификатор (имя) процедуры>(<список фактических параметров>);

For example,

Nod(Abs(E), F, G);

According to the method of transferring actual values ​​to the subroutine in Turbo Pascal 7.0 distinguishes variable parameters, value parameters, constant parameters and arrays open type, open type strings, procedure parameters, function parameters (details in the literature).

A function (unlike a procedure) always returns a single value.

Let's show how the subroutine from the example changes if it is written as a function.

Function Nod(M, N: Integer) : Integer;

While M<>N Do

If M > N Then M:= M - N Else N:= N - M;

So, after the list of parameters, the value type of the function is indicated, and in the body of the function, at least once there is an assignment to a variable whose name matches the name of the function to the corresponding value.

The function call will be as follows:

G:= Nod(Abs(E), F);

In general, a function call can be present in an expression on the right side of an assignment operator, in an output procedure, as an actual parameter in a call to another subroutine, etc.

When solving problems, it is advisable to analyze the condition, write the solution in large blocks (that are not Pascal operators), detail each of the blocks (written in the form of blocks, perhaps still not Pascal operators), etc., continue until each of the blocks is implemented using language operators.

Example 2. Given a natural number n. Swap the first and last digits of this number.

If Impossible(N)

Then WriteLn("Unable to rearrange digits, overflow will occur")

WriteLn("Answer: ", N)

You may notice that it is necessary to detail logical function Impossible, which diagnoses whether a permutation is possible, and the Change procedure, which performs this permutation (if it is possible).

Function Impossible(N: Integer) : Boolean;

If Number(N)< 5

Then Impossible:= False

Else Impossible:= (N Mod 10 > 3) Or

(N Mod 10 = 3)And

(N Mod 10000 Div 10 * 10 + N Div 10000 > MaxInt Mod 10000)

Here it is necessary to detail the Number function, which returns the number of digits in the record natural number(since the Impossible function contains its call, the Number function must precede it in the description section).

Function Number(N: Integer) : Integer;

Var Vsp: Integer;

While N > 0 Do

Vsp:= Vsp + 1; N:=N Div 10

Finally, the last procedure.

Procedure Change(Var N: Integer);

Var Kol, P, S, R: Integer;

Kol:= Number(N);

P:= N Mod 10; (last digit)

If Kol > 1 Then

S:= N Div Round(Exp((Kol - 1) * Ln(10)))

Else S:= 0; (first digit)

R:= N Mod Round(Exp((Kol - 1) * Ln(10))) Div 10;

N:= P * Round(Exp((Kol - 1) * Ln(10))) + R * 10 + S

Subroutines that call themselves are also possible. They are called recursive. Creating such subroutines is a beautiful programming technique, but it is not always advisable due to the excessive consumption of computer memory.

Example 3. Find the maximum digit in the notation of a given natural number.

Program MaxDigit;

Type NaturLong = 1..(High(LongInt));

Function Maximum(N: LongInt) : Digit;

Then Maximum:= N

Else If N Mod 10 > Maximum(N Div 10)

Then Maximum:= N mod 10

Else Maximum:= Maximum(N Div 10)

Write("Enter a natural number: ");

WriteLn("Maximumdigit is ", Maximum(A))

When creating the Maximum function, the following consideration was used: if a number consists of one digit, then it is the maximum, otherwise if the last digit is not the maximum, then it should be looked for among the other digits of the number. When writing a recursive algorithm, you should take care of the boundary condition when the chain of recursive calls breaks and its reverse “unwinding” begins. In our example, this condition is N< 10.

Recursion is discussed in more detail in the next article.

When solving new problems, you can try to use previously written programs. An algorithm previously developed and used entirely as part of other algorithms is called auxiliary. The use of auxiliary algorithms allows you to break the problem into parts and structure it.

The entire program can be divided into two parts: main and auxiliary. In the main part, the simplest processing of information is carried out, access to various auxiliary modules (subroutines).

An auxiliary algorithm can also call other auxiliary algorithms; the length of such a chain of calls is theoretically unlimited. Here and below, the following pairs of words are used as synonyms: algorithm and program, auxiliary algorithm and subroutine, command and operator, program and module. Auxiliary and main algorithms are not in themselves, but in relation to each other.

When using auxiliary algorithms, it is necessary to consider the way in which the values ​​of the source data are transmitted to them and the result obtained from them. Helper Algorithm Arguments these are variables in which the initial data must be placed to solve the corresponding subtask. Results of the auxiliary algorithm these are also variables that contain the results of solving these subproblems, and the result can also be a specific action that the computer performs under the action of the subroutine.

Subroutines can be of two types: a subroutine without parameters and a subroutine with parameters. A subroutine can be called from anywhere in the main program or another subroutine as many times as desired.

When working with subroutines, the following concepts are important: formal and actual parameters. Formal parameters These are the input data identifiers for the subroutine. If formal parameters receive specific values, then they are called actual. Formal parameters can receive specific values ​​only in the program where the given subroutine module is accessed. Type And order the entries for actual parameters must be the same as those for formal parameters. Otherwise, the result of the program will be unpredictable. It follows from this that actual parameters are used when accessing a subroutine from the main one, and formal parameters are used only in the module itself.

A subroutine with parameters is used to record repeatedly repeated actions with different initial data.

When composing subroutines with parameters, the following rules must be observed:

1) each subroutine has its own name and list of formal parameters;

2) the procedure from the main program is called by a call command, which in form is no different from calling an executor command. The result is assigned to one or more variables that are in the list of formal parameters. But the result can, of course, be not only the values ​​of the variables, but some action performed by the computer.

Example 1. We use the algorithm for finding the greatest common divisor of two natural numbers as an auxiliary one in solving the problem: create a program for subtracting fractions ( a, b, c, d natural numbers). Present the result as an ordinary irreducible fraction.

Subroutine.

  1. Enter natural numbers M, N.
  2. If M=N, go to step 5, otherwise go to the next point.
  3. If M>N, then M:=M-N, otherwise N:=N-M.
  4. Go to step 2.
  5. Pass the value M to the main program.
  6. End of subroutine.

Main program.

  1. Enter the values ​​A, B, C, D.
  2. E:=A*D - B*C.
  3. F:=B*D.
  4. If E=0, output the value of E and go to step 9, otherwise go to the next step.
  5. M:=|E|, N:=F, go to the GCD calculation subroutine.
  6. G:= M.
  7. Divide E and F completely by G.
  8. Print the values ​​of E and F.
  9. End of the program.

As can be seen from the example, the declaration of the function subroutine is in the section of function prototype descriptions, and the implementation is after the main function main. The subroutine header contains a list of formal parameters indicating their type, which can be divided into input and output parameters (they are preceded by &). In general, when calling a function with a list of parameters without &, copies of the parameters are used inside the function, which are deleted after execution. The & sign tells the compiler that it is necessary to use the variable itself, and not a copy of it. When calling a function, its name and a list of actual parameters are specified. Formal and actual parameters must correspond in quantity and type.

The description of a function in C++ is as follows:

return_value_type();

For example,

Void Nod(int e, int f, int &k); int f1(float a); long f2();

The function always returns a single value. As you can see from example 1, we used the type void as a return type. Those. indicated to the compiler that our function does not return any value.

Let's show how the subroutine from the example will change if it is written as a function that returns the GCD value itself (without using the return variable).

Int Nod(int m, int n) ( while (m!=n) if (m > n) m -=n; else n -= m; return (n); )

So, in the body of the function there is at least one return command, which specifies what value to return as the value of the function.

The function call in the main one will be as follows:

G = Nod(fabs(e), f);

In general, a function call can be present in an expression: on the right side of an assignment operation, in an output statement, as an actual parameter in a call to another subroutine, etc.

When solving problems, it is advisable to analyze the condition, write the solution in large blocks (which are not C++ statements), detail each of the blocks (written in the form of blocks, perhaps still not C++ statements), etc., continue until until each of the blocks is implemented using language operators.

Example 2. Given a natural number n. Swap the first and last digits of this number.

Here it is necessary to detail the Number function, which returns the number of digits in the representation of a natural number (since the Impossible function contains its call, the Number function should precede it in the prototype description section).

Subroutines that call themselves are also possible. They're called recursive. Creating such subroutines is a beautiful programming technique, but it is not always advisable due to the excessive consumption of computer memory.

Example 3. Find the maximum digit in the notation of a given natural number.

When creating the Maximum function, the following consideration was used: if a number consists of one digit, then it is the maximum, otherwise if the last digit is not the maximum, then it should be looked for among the other digits of the number. When writing a recursive algorithm, you should take care of the boundary condition when the chain of recursive calls breaks and its reverse “unwinding” begins. In our example this condition N

Recursion is discussed in more detail in the following article.

Control questions and tasks
  1. What algorithms are called auxiliary algorithms?
  2. How many auxiliary algorithms can be present in the main algorithm?
  3. Can auxiliary algorithms written to solve this problem be used to solve other problems where their use would be appropriate?
  4. What parameters are called formal? factual?
  5. What correspondence should be observed between formal and actual parameters?
  6. Can there be more actual parameters of a procedure (function) than formal ones? What about less?
  7. Are there subroutines without parameters?
  8. Are there any restrictions on the number of subroutine parameters? If not, then how is this number limited in C++?
  9. In which section are subroutines declared and implemented in C++?
  10. What type can a function value be?
  11. Explain the method of sequential detailing in program development.
  12. What subroutines are called recursive?
  13. What is a boundary condition when organizing a recursive subroutine?

Containing a description of a specific set of actions. A subroutine can be repeated multiple times caused from different parts of the program. In programming languages, there are special syntactic means for designing and using subroutines.

Purpose of subroutines

Subroutines initially appeared as a means of optimizing programs in terms of the amount of memory they occupy - they made it possible not to repeat identical blocks of code in a program, but to describe them once and call them as needed. By now this function subroutines have become auxiliary, their main purpose is to structure the program for the purpose of making it easier to understand and maintain.

  • Selecting a set of actions into a subroutine and calling it as needed allows you to logically select an integral subtask that has standard solution. This action has one more advantage (in addition to saving memory) over repeating similar actions: any change (error correction, optimization, expansion of functionality) made in the subroutine is automatically reflected in all its calls, while when duplicating each change must be made in every occurrence of modified code.
  • Even in cases where a subroutine contains a one-time set of actions, this is justified, since it allows you to reduce the size of the entire blocks of code that make up the program, that is, to make the program more understandable and understandable.

Advantages

The benefits of breaking a program into subroutines include:

  • Decomposition of complex program task on simple steps: It is one of the two main tools of structured programming and data structures
  • Reducing duplicate code
  • Opportunity reuse code in other programs
  • Dividing a large software task among different programmers, or different stages of a project
  • Hiding implementation details from routine users
  • Improved tracing (most languages ​​provide a way to get a trace of a call that includes the names of the routines involved and perhaps even more information such as file names and line numbers). Without decomposing code into subroutines, debugging would be seriously difficult.

The mechanism of subroutines, their description and call

In the following Pascal example, subprog is called three times from the main program:

Program SubProgExample ; procedure subprog ; begin // start of the body of the subroutine WriteLn("Bye"); end ; // end of the subroutine body begin WriteLn("Hello"); subprog ; // 1st call subprog ; // 2nd call subprog ; // 3rd call end .

The result of executing such a program will be the output of the line “Hello” and three lines “Bye”.

To save and restore the execution context of the calling procedure, in order to eliminate side effects associated with possible unwanted changes in the machine registers used, the compiler generates special sequences of commands for each procedure, called the prologue and epilogue of the procedure.

Some programming languages ​​(for example, Pascal, Ada, Modula-2) allow the description of nested subroutines, that is, placing subroutines inside other subroutines. Such nested subroutines can only be used in the subroutine in which they are described. In other cases (for example, in the C language), nesting subroutines is not allowed. Nesting subroutines does not provide any fundamental advantages, but it can be convenient for a more logical structuring of the program (if some subroutine is used only in some other subroutine, it is logical to place the first one in the second).

Routine parameters

Assignment of parameters

Subroutines are often used to repeatedly perform stereotyped actions on different data. A subroutine usually has access to data objects described in the main program (at least some of them), so in order to transfer the processed data to the subroutine, it is enough to assign them, for example, to global variables. But this path is not particularly convenient and is fraught with errors.

To ensure controlled transfer of parameters to the subroutine and return of results from it, a mechanism is used parameters. Parameters are described when describing a subroutine (in its header) and can be used inside a procedure in the same way as variables described in it. When calling a procedure, the values ​​of each of the parameters are indicated in the call command (usually after the name of the called subroutine).

Program SubProgExample2 ; // Description of the subprog subroutine procedure subprog (Line : String ) ; // Header including the name of the subroutine begin // start of the body of the subroutine WriteLn(Line); end ; // end of the subroutine body begin WriteLn("Hello"); subprog("Good bye,"); // 1st call subprog ("my love," ) ; // 2nd call subprog ("good bye!" ) ; // 3rd call end .

In the example given, the parameter Line subroutines subprog in each call it receives a different value, due to which not the same lines are output, but different ones.

Formal and actual parameters

To distinguish the parameters of a subroutine, described in its head and body, from the parameters specified when calling the subroutine, formal and actual parameters are used. Formal parameters are specified when declaring or defining a subroutine, and actual parameters are specified directly when calling it. So, in the last example the parameter Line in the header and body of the subroutine subprog is a formal parameter, and the string "Good bye", used in the first call to this routine is an actual parameter. When a subroutine is called, the actual parameters specified in the call command become the values ​​of the corresponding formal parameters, which ensures the transfer of data to the subroutine.

Method for passing parameters to a subroutine

There are several ways to pass parameters to a subroutine.

  • Passing parameters by value. The formal parameter is assigned meaning actual parameter. In this case, the formal parameter will contain a copy of the value present in the actual one, and any action made within the subroutine on the formal parameters will not affect the actual parameters. So, if a variable is used as an actual parameter, and inside the subroutine the value of the corresponding formal parameter is changed, then the actual parameter will remain unchanged.

int func1(int x)

( x=x+2; return x;

  • Passing parameters by reference. The formal parameter can be placed myself actual parameter (usually this is implemented by placing a reference to the actual parameter in the formal parameter). In this case, any change in the formal parameter in the subroutine will be reflected in the actual parameter - both parameters are the same when calling the subroutine. Parameters passed by reference make it possible not only to pass parameters inside a subroutine, but also to return calculated values ​​to the call point. To do this, the parameter within the subroutine is simply assigned the desired value, and after the subroutine returns, the variable used as the actual parameter is given that value.
  • Passing parameters by name. An arbitrary expression can be placed in a formal parameter. In this case, the calculation of this expression will occur inside the subroutine at the moment when its value is required. If this value appears several times, then it will also be calculated several times. Parameters passed by name make it possible to write fairly universal subroutines. This method of passing parameters is used, for example, in the ALGOL or ALGOL 68 languages.
  • Passing parameters via the stack. This is actually a type of parameter transfer by value “with manual drive”; in this case, there is no concept of formal and actual parameters. All parameters are on the stack, and their types, number and order are not controlled by the compiler. This approach is implemented in the Forth language.

A programming language may provide the ability to pass parameters to subroutines either by value alone, by value and by reference, or by name and value. In the last two cases, separate syntactic constructions are used to distinguish between ways of passing a parameter (in Pascal this is keyword var when describing the parameter). In fact, if the language contains the concept of a link (pointer), then you can do without passing a parameter by reference (it can always be modeled by describing a parameter of the “link” type), but this feature is convenient, since it allows you to work with a formal reference parameter without dereferencing, and also increases the reliability and security of the program.

This is a special type of subroutine, which, in addition to receiving parameters, performing actions and transmitting work results through parameters, has one more feature - it must always return a result. A function call is, from a programming language point of view, an expression; it can be used in other expressions or as the right side of an assignment.

  • A procedure is an independent named part of a program that, after being described once, can be called repeatedly by name from subsequent parts of the program to perform certain actions.
  • In -like languages, a subroutine is always declared as a function. The procedure is implemented as a function of type void, that is, having an “empty” type and, accordingly, not returning any value.

    Subroutines that are part of classes in object programming languages ​​are usually called methods. This term refers to any subroutines that are members of a class, both functions and procedures; when clarification is required, they talk about methods-procedures or methods-functions.

    The purpose of the lesson:

    • give students an idea of ​​subroutines and how they can be used;
    • show with examples the mechanism for implementing subroutines using procedures.

    Tasks:

    • Educational:
      • use special terms when answering questions
      • develop the ability to apply acquired knowledge in the process of creating and debugging programs
    • Developmental:
      • develop attention, observation, memory, logical thinking
      • develop the ability to analyze and systematize the material necessary for work
      • develop skills to make decisions independently
    • Educational:
      • follow safety rules in the computer science classroom
      • cultivate a culture of behavior, have your own view on how to solve a given problem, be able to listen to the opposing point of view

    Plan

    I. Repetition of material.
    II. Learning new material.
    III. Lesson summary.
    IV. Homework.

    DURING THE CLASSES

    I. Repetition of material

    1. What is the structure of the program?
    2. Is a program title required?
    3. List description sections
    4. What function words are used to describe variables?
    5. What function word is the beginning of the main part of the program?
    6. How does the program end?

    PROGRAM NAME; (you don’t have to write)
    1.CONST
    2.TYPE
    3. VAR
    4. PROCEDURE, FUNCTION
    BEGIN
    Program body
    END.

    And now we will solve the KEYWORD by filling it out - we will repeat the operators, function words of the Pascal language ( Annex 1 ).
    (Completed KEYWORD – Appendix 2 )

    II. Learning new material

    When creating a program to solve a complex problem, programmers divide that task into subtasks, subtasks into even smaller subtasks, and so on, down to easily programmable elementary tasks. Over time, each programmer after a while has a large set of his own blanks, extraordinary solutions, etc., which he would like to use in all his creations.
    Language Pascal programming allows you to divide a program into separate parts called subroutines. The term subroutine itself indicates that it is similar to and subordinate to the main program. Subroutines perform three important tasks that make programming much easier:

    • eliminate the need to repeatedly repeat similar fragments in the program text, i.e., reduce the size of the program;
    • improve the structure of the program, making it easier to understand when parsing;
    • reduce the likelihood errors appear, increase resistance to programming errors and unforeseen consequences during modification.

    Thus, subroutine is a repeating group of operators, designed as an independent program unit. It is written once, and in the appropriate places in the program only access to it by name is provided.
    General principles of selection subroutines:

    – if it is necessary to rewrite the same sequences of commands in a program, then it is worthwhile to format this sequence of commands in the form of a subroutine;
    – It is useful to break a program that is too long into its component parts, just as a book is divided into chapters. At this the main program becomes like a table of contents;
    – when solving a problem, problems may arise that are too complex. It is more expedient to debug them separately in small programs. Adding these programs to the main task is easy if they are formatted as subroutines;
    – everything that you did well in one program, you will want to transfer to new programs.

    IN Pascal language The mechanism of subroutines is implemented in the form of PROCEDURES (PROCEDURE) and FUNCTIONS (FUNCTION), which are introduced into the program using their description, but their structure is the same as the structure of the program. They differ in purpose and method of their use.

    Procedures are designed to perform a certain sequence of actions.
    To use a subroutine, its procedure must be described and you must be able to access it.

    Description:

    1. Choose a name for her.
    2. Define parameters.
    3. Create a sequence of actions that must be performed to obtain a result.

    Appeal: calling to perform specified actions for specific parameter values.

    Options there are the following types:

    I. Global– parameters are described in the head module and are available to any subroutine.
    I. Local– are used only in the procedure, they may or may not be, described after the word VAR, indicating the type.

    II. Formal– are described in the procedure header, these include input and output parameters.
    III. Inputs are and IV. Parameters – values ​​are described separated by commas and indicating the type. They are not saved when exiting the procedure.
    III. Weekends are also IV. Parameters - variables are described after the word VAR, separated by commas, indicating the type, and are saved when exiting the procedure.
    These parameters are described in parentheses after the procedure name

    II. Actual - in the head module when calling the procedure.
    When called (contacted), formal parameters are replaced with actual ones.

    Formal and actual must coincide according to 3 characteristics:

    • in count
    • type
    • in order of occurrence.

    Description of the procedure

    Any procedure begins with a header, which is a mandatory part of it (unlike from the title programs). It consists of function word Procedure followed by the name of the procedure, and in round in brackets – a list of formal parameters. After the title there may be the same sections as in the program. So the general view will be as follows:

    Procedige<имя>(formal parameters);
    VAR (description of local parameters, they may or may not exist)
    begin
    procedure body
    end; (end of procedure)
    BEGIN (head module)
    Actual parameters
    END.
    Using a subroutine - procedure, we will consider several tasks

    1. Create a program for adding 2 numbers, values ​​are entered from the keyboard.

    2. Create a program for finding the maximum of four numbers entered from the keyboard.

    uses art;
    var a,b,s,c,d:real;
    procedure maxim (x,y: real; var s: real);
    begin
    if x
    end;

    begin
    clrscr;
    writeln("bbedite 4 chisla ");readln(a,b,c,d);

    We put the larger of the two numbers A and B into the variable S.

    maxim(a,b,s);

    We put the larger of the two numbers C and S into the variable S.

    maxim(c,s,s);

    We put the larger of the two numbers D and S into the variable S.

    maxim(d,s,s);)
    writeln("max=",s:3:I);
    readkey;
    end.

    Debug on the computer.

    III. So, we got acquainted with new concepts: subroutine, procedure. We learned what parameters are needed to work with procedures. The structure of the procedure. Description.

    IV. Homework

    The triangle is given by the coordinates of the vertices, calculate the perimeter and area. Calculate the lengths of the sides using the procedure.

    – formula for calculating length: A =

    What function in Pascal means square root? – SQRT means squaring – SQR

    – the perimeter is found using the formula P = A + B + C
    – formula for finding area: S =
    – how many times will we go through the procedure? - 3 times

    When solving many problems, it becomes necessary to perform actions multiple times, with different values. To reduce the size of the program, it is advisable to separate repeated actions into a subroutine, which describes the procedure for the actions performed. Usage subroutines in the program is advisable for two reasons:

    • The subroutine allows you to save memory. Each subroutine that exists in the program is loaded into RAM in one copy, and it can be called from different places in the program;
    • the use of subroutines is advisable from the point of view of modern modular programming methods. In accordance with the methodology, the solution algorithm is represented as a sequence of subroutines. Each subroutine can be divided into smaller subroutines, and those, in turn, into subroutines of a lower level.

    Pascal has two types of program units called subroutines:

    • procedures;
    • functions.

    A procedure and a function can be represented as relatively independent fragments that have a special structure and are given a name. A procedure or function is called by mentioning its name in the program text. The difference between a function and a procedure is that the result of executing the function's statements is always a single value assigned to the function name. In this regard, the function call in the program is carried out on the right side of the assignment operator, along with other operands. A procedure in a program is called by mentioning its name.

    Pascal has two types of procedures and functions:

    • standard;
    • non-standard.

    Standard ones are part of the language itself and are found in the language in so-called standard libraries, and such libraries are found in the language in the form of independent program units (modules). The Turbo-Pascal language has several standard modules: System, Dos, WinCrt, Printer, Graph, Overlay. They are connected in Uses. This requirement does not apply to System, which contains the main procedures and functions, since this module is automatically included by the compiler.

    Non-standard ones must be described so that the compiler can establish a connection between the call operator and the actions that are present in the procedure or function.

    The description of procedures and functions can be implemented in two ways:

    • in the program description section;
    • in separately compiled program units called modules.

    Descriptions of procedures and functions outwardly look like program descriptions, but instead of the program title, the title of the function or procedure is written. Describing a subroutine means specifying its title and body. The header contains parameters and declares the name of the subroutine. In a function, the type of the returned result is indicated in the header. Behind the header is the body of the subroutine, which consists of sections: descriptions and statements. In a subroutine, the description section can describe lower-level subroutines. Structurally, a program using subroutines looks like this:

    A subroutine at any level usually has many constants, types, names, and lower-level subroutines. All program objects that are described inside a subroutine are localized within it, that is, they are not visible or accessible outside the subroutine. In the above structure, you can access subroutine A and subroutine B from the main program, but you cannot access nested subroutines A1 and B1. Names declared in a subroutine are called local names. All names accessible to a subroutine from a program or top-level subroutine are called global. Names localized in a subroutine may coincide with global names that were previously declared, in which case the local name closes the global one, that is, makes it inaccessible.

    Pascal uses the principle of using identifiers, based on the fact that any name can be used if it has already been declared.

    Declaring subroutines in Pascal

    Function declaration:

    Function [name] ([list_of_formal_parameters]:[type]):[type];

    [function_description_section];

    [function_body_operators];

    [name]:=[result_of_function_body_operators];

    Function is a function word. [name] - name identifier. [list_of_formal_parameters] - parameters in general form. [type] - type of parameters. It has a description section and an operator section. The function is called in the operators section:

    [variable]:=[name](list_of_formal_parameters);

    When declaring a function, formal parameters are separated from each other by a semicolon, and parameters of the same type are separated by a comma. The list of actual parameters when called must match the order and type of the formal parameters. The actual parameters of the call can be the names of variables that must first be defined. A function can have an arbitrary number of input parameters and one single result of the function. Procedures are used if the program needs to obtain several results, that is, a subroutine implemented as a procedure can have an arbitrary number of input and output parameters.

    Procedure declaration:

    Procedure [name] ([list_of_input_parameters]:[type];

    Var [output_formal_parameter_1]:[type];

    Var [output_formal_parameter_K]:[type];):[type];

    [procedure_description_section];

    [procedure_body statements];

    Since a procedure can return multiple output parameters, each output parameter in the procedure header is followed by a separate Var function word.

    The procedure is called by mentioning the name and the list of actual parameters, while values ​​and predefined variables can be used as input actual parameters, and only variables as output actual parameters.

    Calling the procedure:

    [name](actual_parameters_list);