When creating a subroutine. Subroutines (procedures and functions)

A 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.

Using a subroutine allows, firstly, to reduce the size of the program, secondly, it improves the structure of the program in terms of its readability and clarity, and thirdly, it reduces the likelihood of errors and facilitates the debugging process.

In the Pascal language, the mechanism of subroutines is implemented in the form of PROCEDURES and FUNCTIONS, which are introduced in the program using their description, but their way of using them.

Procedure- it is an independent part of a program that can be called by name to perform specific actions. A procedure cannot act as an operand in an expression. Mentioning the name of a procedure in the text of a program causes the procedure to be activated and is called its call. For example,

Delay (10); causes a 10ms delay in program execution.

Function is similar to a procedure, but there are two differences: the function passes a scalar value to the call point; the name of a function in an expression can come out as an operand. For example, the SQR(x) function will square the value of an integer or real value X and pass the calculated value of the square of the variable X to the call point.

All procedures and functions of the Pascal language are divided into two groups:

à Built-in (standard) - included in the language and called for execution by a strictly fixed name.

à User-defined – developed and available by the user himself.

When calling a subroutine defined by the programmer, the work main program pauses for a while and the called subroutine begins to execute.

In a program, procedures and functions are described after its variables section, but before the beginning of its main part, that is, before Begin begins this part.

Transferring data from the main program to a subroutine and returning the result of a function execution is carried out using parameters.

Parameter is a variable that is assigned a value within a specified application.

Actual parameters - These are the parameters that are passed to the subroutine when communicating with it.

Formal parameters– these are variables that are fictitiously present in the procedure and determine the type and place of substitution of the actual parameters on which actions are performed.

Parameters - variables- these are the formal parameters preceded by the auxiliary word Var. They are passed by reference (the address of the actual parameter is passed) when it is necessary to pass some new values ​​to the point of calling the procedure from the program, that is, when it is necessary that changes in the procedure body of the values ​​of formal parameters lead to changes in the corresponding actual parameters, thus they receive a new meaning.

Parameters - values- there is a word in front of them Var is not set and is transmitted by value, that is, only a copy of the value of these parameters is transmitted, inside the procedure you can perform any actions with these formal parameters (allowed for its type), but any changes to them do not affect the values ​​of the corresponding actual parameters in any way, are not reflected in any way on the values ​​of the corresponding actual parameters, that is, what they were before the procedure was called, then they will remain the same after its completion.

Subroutine – a relatively independent part of the program, which has its own name and performs certain actions.

Subroutines increase the reliability and clarity of programs, because allow each program block to be developed and debugged independently (for example, by different people).

Subroutine structure almost completely repeats the structure of the entire program and consists of the following parts:

    subroutine title

    descriptions section

    body of the subroutine

There are two types of subroutines in Pascal − procedures And functions. They differ in purpose and method of their use. Procedures serve to perform a certain sequence of actions aimed at changing the program environment (changing variable values, input/output of data, etc.). Functions

to calculate the value of an expression.

5.1 Procedures <имя>procedure

<раздел описаний>;

(list of formal parameters);

< begin>;

procedure body Example 1:

The procedure for calculating and displaying a cube of a number.

procedure cube(x: real); Specifying the name of a procedure in a program causes the procedure to be activated and is called challenge

For example:

Parameters are used to exchange information between the main program and the procedure, which give the procedure versatility.

Example 2: A program that displays the following:

var a,b: integer;

procedure Stars; (no parameters)

var i: integer;

for i:=1 to 9 do write(‘*’);

for a:=1 to 4 do

writeln(‘a=’,a,’ b=’,b);

Stars;

(call procedure Stars)3:

var a,b: integer;

Example

var i: integer;

procedure Stroka(ch: char, n: integer);

for i:=1 to n do write(ch);

Stroka(‘+’,4);

writeln(‘a=’,a,’ b=’,b);

for a:=1 to 3 do

Stroka(‘*’,8);

Let's analyze the call to the procedure Stroka('*',8): '*' and 8 are the actual parameters (i.e. those indicated in parentheses after the procedure name when calling it), they are assigned when calling the formal parameters ch and n (i.e. .e. those indicated in brackets after the name of the procedure when describing it). Comment:

the number, order and type of parameters when calling a procedure must match the number, order and type of parameters specified when describing the procedure.:

Result on screen

  • 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

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

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

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.
The Pascal programming language 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 of errors, 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 the 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 the 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. Thus, general form 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);
(list of formal parameters);
if x
end;

(list of formal parameters);
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);

In the variable S we enter the larger of the two numbers C and 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

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 of subroutines has become auxiliary; their main purpose is to structure the program for the purpose of making it easier to understand and maintain.

  • Isolating a set of actions into a subroutine and calling it as needed allows you to logically isolate a holistic subtask that has a 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...

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 ;

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 procedure subprog; WriteLn(Line); // start of the body of the subroutine end ;

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 subprog("Good bye," ) ; subroutines // 2nd call subprog("good bye!" ) ; 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 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+1; 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.

void func2(int &x) ( x=x+1; )

  • 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 only (this is done in the C language), or by value and by reference (this is implemented in Pascal, Ada, C++), or by name and value (this is implemented in the Algol and Algol 68). In the last two cases, separate syntactic constructions are used to distinguish between ways of passing a parameter (in Pascal this is the 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.

Natural restrictions are imposed on parameters passed by reference: the actual parameter substituted in place of such a parameter when called must be a variable (that is, have an address), and in strongly typed languages, it must also have exactly the same data type.

Types of subroutines

High-level programming languages ​​use two types of routines: procedures and functions.

  • A function is a subroutine of a special type, which, in addition to receiving parameters, performing actions and transmitting work results through parameters, has one more possibility - it can return 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. For more details, see the 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 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 a subroutine in Turbo Pascal 7.0, there are 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 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 a natural number (since the Impossible function contains its call, the Number function should 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("Maximum figure 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.