procedures and functions. Procedures and functions in Pascal

procedures and functions.  Procedures and functions in Pascal
procedures and functions. Procedures and functions in Pascal

8th grade. Programming on ABC language Pascal

Informatics teacher, NIS, Uralsk FMN Zelenov Boris Aleksandrovich


  • Students use procedures and functions to solve problems
  • Students learn to solve large problems by breaking them down into smaller ones.

  • To form the concept of procedures and functions in a programming language.

  • Students know the concepts of "procedures" and "functions", determines the formal and actual parameters

Expected Results - Descriptors:

1.Knows the definition of "procedure"

2.Knows the definition of "function"

3. Defines the actual and formal parameters

4.Distinguishes parameter values ​​and variables

5. Finds a call to a procedure or function in the program code



Elvira's standard plan

1. Remove papers

2. Water the flowers

3. Wash the desks

4. Wipe glass

End of algorithm

How to improve the organization of this process?




Lesson topic

Routines:


Ishki bagdarlam

subroutine

Procedure

Procedure

Parametler

Useful phrases:

To pass the values ​​of variables to the procedure (function), the actual parameters are used ...

In order to describe the procedure, one should first ...., then ...


The concept of a subroutine

Definition

subroutine is a separate functionally independent part of the program.

subroutines

Procedures


  • eliminate the need to repeatedly repeat similar fragments in the text of the program;
  • improve the structure of the program, making it easier to understand;
  • increase resistance to programming errors and unforeseen consequences during program modifications.

  • Draw a fence using a programming language

In this task, you can create a procedure that will execute the algorithm for drawing one fragment (fence), and then constantly refer to this procedure, changing the initial position of the pen


  • Describe how to rationally draw a Christmas tree in a programming environment

  • They are independent fragments of programs, designed in a special way and having their own name.

Interaction between main program and subprogram



block diagram

  • Subroutine call block (procedure or function)

Subroutine name (procedure or function)


block diagram


The description of the procedure looks like:

procedure name(list of formal parameters); description section begin operators end ;


The function description looks like:

function name(list of formal parameters): return type;

description section begin operators end ;


Location in the program

program ...;

//Description section Uses, Const, Var, ...

procedure A ;

begin ....... end ;

procedure B ;

begin ........ end ;

Function C ;

begin ........ end ;

//Main program

begin ........ end .


  • The difference between a function and a procedure is that the result of the execution of the operators that form the body of the function is always a single value, so the call to the function can be used in the corresponding expressions along with variables and constants.

Procedures

Functions

Can have multiple results or perform some action

It has only one result, the type of which is specified separately when declaring the function.

The results can be any type of arrays, strings, numbers, etc.

The result can only be a real, integer, or char value.

The procedure call command is a separate command that is used independently.

A function call can only be used as a component of an expression of the appropriate type.

The body of a function must contain at least one assignment operator, on the left side of which the name of the function is indicated.


b then max:=a else max:=b; MaxNumber:= max; end;" width="640"

Procedure or function?

MaxNumber(a,b: integer): integer;

var max: integer;

MaxNumber:= max;


b then max:=a else max:=b; end;" width="640"

Procedure or function?

MaxNumber(a,b: integer; var max: integer);

if ab then max:=a else max:=b;


Procedure or function?

ChangeColor(C1, C2: Word);

TextBackGround(C2)


Procedure or function?

Add(X, Y: Integer): Integer;


Actual

  • Indicated in the main program section

Formal

  • Specified in the subprogram
  • Specified in the subprogram

A procedure call is made by a statement that has the following format:

procedure name (list of actual parameters);

  • List of actual parameters is their enumeration separated by commas.

  • In the Pascal language standard, parameters can be passed in two ways - by value and by reference. Parameters passed by value are called value parameters passed by reference - variable parameters. The latter are distinguished by the fact that they are preceded by the service word var in the heading of a procedure (function).

Passing parameters. Formal parameters

Variables

Values

Parameters by value

Formal parameters

Variables


Formal parameters

Parameters by value

  • In the first method (passing by value), the values ​​of the actual parameters are copied into the corresponding formal parameters.

Procedure

Name Procedure (a, b: integer);

Main program

If these values ​​are changed during the execution of the procedure (function), the initial data (actual parameters) cannot change


Var c, d: integer;

  • When passing by reference, all changes that occur in the body of a procedure (function) with formal parameters lead to immediate similar changes in the actual parameters corresponding to them.

Procedure

Name Procedure (a, b: integer, Var c: real);

Main program

Changes occur to the variables of the calling block, so output parameters are passed by reference. When called, the actual parameters corresponding to them can only be variables.


You write:

1. Actual parameters ___________

Procedure Kvad(R: real; var S: real);

2.Formal parameters ___________

3. Formal parameters-values ​​__________

5.Procedure name ___________

6. Calling the procedure from the program _____________________


Interactive task

http://www.bzfar.net/load/podprogrammy_procedury_i_funkcii_parametry/23-1-0-498


Elvira is the class leader. She will have to make a plan for the general cleaning in the classroom: remove the papers, water the flowers, wash the desks, wipe the windows. What is the best way for her to organize her work? Help Elvira.


Elvira Advanced Plan

Routines:

Arsen - removes papers

Mila watering flowers

Vitaly - washes desks

Indira - wipes glass

1. Run Arsen

2. Run Mila

3. Run Vitaly

4. Run Indira

End of algorithm


  • What new structures of the programming language have we met today?
  • Name the studied parameters
  • How are parameters passed to a procedure?

  • Lesson summary
  • Find Definitions: "Local Variables" and "Global Variables"
  • Compose two tasks in which procedures or functions can be used.

  • How would you define the topic of the lesson? (make up your own name)
  • What do you think you should learn in the next lesson?

Let's meet

next lesson!

To enjoy preview presentations create an account ( account) Google and sign in: https://accounts.google.com


Slides captions:

Procedures and functions in Pascal. Recursion Performed by the teacher of computer science GBOU school 1362 Sanina Marina Sergeevna

Subroutine - an autonomous part of the program that performs a certain algorithm and allows access to it from different parts general program. Using subroutines allows you to implement one of the most modern programming methods - structured programming.

subroutines procedure function PROCEDURE FUNCTION

Procedures and functions in Pascal are declared in the description section behind the variable section.

Functions and procedures have parameters (variables that pass a value). They are of two types: 1) Formal - those that are in the description of the subroutine 2) Actual - those that are transferred from the main program to a function or procedure. The actual parameters must match the formal ones in number, order, and type.

Also, the subroutine has variables. with whom she will continue to work. They are again divided into two types: 1) Global variables, that is, acting in the entire program 2) Local - those that act only in a procedure or function

Procedures Used when a subroutine needs to get multiple results. There are two types of procedures: with a parameter; without parameter.

The procedure structure is similar to the program structure and consists of a header and a block (procedure body). procedure ProcedureName; var … begin …//Procedure body end ; begin // main program body end .

Procedures without parameters procedure pr; var i: integer ; begin for i:=1 to 60 do write (‘ * "); writeln ; end . begin pr ; end. This program outputs a string of 60 asterisks.

Procedure with a parameter. Write a program to exchange places of two numbers c=5 and d=7 program obmenDan ; var c,d:integer ; procedure obmen(a,b:integer); var m:integer; beginm:=a; a:=b; b:=m; writeln(a,b); end; begin writeln("Enter 2 numbers: "); readln(c, d); obmen(c,d) ; writeln(c," ",d); end.

Analysis of the problem 1) when calling the obmen procedure with two parameters 5 and 7, the numbers 5 and 7 are also placed in the variables a and b, respectively: с 5 d 7 a 5 b 7

In order for the variables c and d , a and b to refer to the same memory cells (if the values ​​of a and b change, then the values ​​of c , d will also change) when describing the formal parameters, add the word VAR before the necessary variables: procedure obmen (var a,b:integer); c 5 d 7 a b

Functions The set of built-in functions in Pascal is quite wide (ABS, SQR, TRUNC, etc.). If a new, non-standard function is included in the program, then it must be described in the program text, after which it can be accessed from the program. The call to the function is carried out on the right side of the assignment operator, indicating the name of the function and the actual parameters. A function can have its own local constants, types, variables, procedures, and functions. The description of functions in Pascal is similar to the description of procedures.

Distinctive features of functions: - execution result - one value, which is assigned to the function name and transferred to the main program; - the function name can be included in the expression as an operand.

Function description: function () : type; (local name description section) Begin (executable statements section) :=; ( required parameter ) End;

Function call: := (); 1 . On the right side of the assignment operator. 2. In an expression in the condition of the branching operator. 3. In the output procedure, as a result of the function.

Recursion Procedures and functions in Pascal can call themselves, i.e. have the recursive property. A recursive function must necessarily contain a recursive termination condition so as not to cause the program to loop. Each recursive call creates a new set of local variables. That is, variables located outside the called function are not changed.

Compose a recursive function that calculates the factorial of a number n as follows: n ! = 1 if n= 1 n!= (n -1)! n if n > 1

function f(n: integer): integer ; begin if n = 1 then f:= 1 else f:= n * f (n -1); (function f calls itself) end ;

Tasks Change the values ​​of variables a, b, c so that they are arranged in non-decreasing order (a ≤ b ≤ c). Given n integers. Find among them the number whose sum of digits has the maximum value.


Subroutines Often in a task you want to repeat a certain sequence of statements in different parts of the program. In order to describe this sequence once, and apply it many times, subroutines are used in programming languages. A subroutine is a specially designed program block for its further reuse in the main program. The use of subroutines allows you to implement one of the most modern programming methods - structured programming.


Subroutines solve three important tasks that greatly facilitate programming: 1. eliminate the need to repeatedly repeat similar fragments in the program text, i.e. reduce the scope of the program; 2. improve the structure of the program, making it easier to understand when parsing; 3.reduce the possibility of errors, increase resistance to programming errors and unforeseen consequences during modification.


Procedures and Functions There are two kinds of subroutines in Pascal: procedure (PROCEDURE) and function (FUNCTION). Procedures and functions in Pascal are declared in the description section behind the variable section. Program ProgramName; VAR … // section of the description of variables of the main program; procedure ProcedureName; var … begin …//Procedure body end; begin //main program body end.


Functions and procedures have parameters (variables that pass a value). They are of two types: 1) Formal - those that are in the description of the subroutine 2) Actual - those that are transferred from the main program to a function or procedure. The actual parameters must match the formal ones in number, order, and type.




Procedures Procedures are used when several results are to be obtained in a subroutine. There are two types of procedures in Pascal: procedures with parameters and without parameters. A procedure is called by the name of the procedure, followed by actual parameters. When a procedure is called, a one-to-one correspondence is established between the actual and formal parameters, then control is transferred to the procedure. After the procedure is executed, control is transferred to the next, after the procedure call, operator of the calling program.


Example 1: A procedure with no parameters that prints a string of 60 asterisks. procedure pr; var i: integer ; begin for i:=1 to 60 do write(* "); writeln; end; begin pr; end.


Example 2. Write a program to exchange places of two numbers c=5 and d=7 program obmenDan; var c,d:integer; procedure obmen(a,b:integer); var m:integer; beginm:=a; a:=b; b:=m; writeln(a,b); end; begin writeln("Enter 2 numbers: "); readln(c, d); change(c, d); writeln(c," ",d); end. c5 d 7 a 5 b 7 they are in other memory cells


In order for the variables c and d, a and b to refer to the same memory cells (if the values ​​of a and b change, then the values ​​of c and d will also change) when describing the formal parameters, add the word VAR before the necessary variables: procedure obmen (var a,b:integer); c5 d 7 a b


Example 3. Given 3 different arrays of integers (the size of each does not exceed 15). In each array, find the sum of the elements and the arithmetic mean. program proc; var i, n, sum: integer; sr: real; procedure work (r:integer; var s:integer; var s1:real); var mas: array of integer ; j: integer begin s:=0; for j:=1 to r do begin read(mas[j]); s:=s+mas[j]; end; s1:=s/r; end;


(main program) begin for i:=1 to 3 do begin write ("Vvedite razmer ",i, " masiva: "); readln(n); work(n, sum, sr); (calling work procedure) writeln("Summa elementov = ",sum); writeln("Srednearifmeticheskoe = ",sr:4:1); end; end.


The result of the program's work: The program calls the work procedure three times, in which the formal variables r, s, s1 are replaced by the actual n, sum, sr. The procedure performs the input of array elements, calculates the sum and average value. The variables s and s1 are returned to main program, therefore, before their description, the service word var is placed. The local parameters mas, j are valid only in the procedure. Global - i, n, sum, sr are available throughout the program.


Functions in Pascal The set of built-in functions in Pascal is quite wide (ABS, SQR, TRUNC, etc.). If a new, non-standard function is included in the program, then it must be described in the program text, after which it can be accessed from the program. The call to the function is carried out on the right side of the assignment operator, indicating the name of the function and the actual parameters. A function can have its own local constants, types, variables, procedures, and functions. The description of functions in Pascal is similar to the description of procedures.




Example 4. Write a subroutine-function of degree a x, where a, x are any numbers. Let's use the formula: a x = e x ln a program p2; var f, b, s, t, c, d: real; ( global variables) function stp (a, x: real) : real; vary: real; (local variables) begin y:= exp (x * ln (a)) ; stp:= y;(assigning the function name of the subroutine calculation result) end; (function description finished) begin d:= stp(2.4, 5); (calculating powers of various numbers and variables) writeln (d, stp (5,3.5)); read(f, b, s, t); c:= stp(f, s)+stp(b, t); writeln(c); end.


Functions A subroutine is a part of a program designed as a separate syntactic construction and provided with a name (an independent program block) for solving individual tasks. Procedure description: procedure () (local name execution section) Begin (statement execution section) End; Function description: function (): type; (local name declaration section) Begin (executable statement section) := ; (required parameter) End; Procedure call: (); Function call: := (); 1. On the right side of the assignment operator. 2. In an expression in the condition of the branching operator. 3. In the output procedure, as a result of the function. Description of subroutines Procedures


Recursion Procedures and functions in Pascal can call themselves, i.e. have the recursive property. A recursive function must necessarily contain a recursive termination condition so as not to cause the program to loop. Each recursive call creates a new set of local variables. That is, variables located outside the called function are not changed.


1 function f(n: integer): integer; begin if n = 1 then f:= 1 else f:= n * f (n -1); (function f calls itself" title="Example 5. Write a recursive function that computes the factorial of n as follows: n! = 1 if n= 1 n!= (n -1)! n if n > 1 function f (n: integer): integer; begin if n = 1 then f:= 1 else f:= n * f (n -1); (function f calls itself" class="link_thumb"> 19 !} Example 5. Write a recursive function that calculates the factorial of a number n as follows: n! = 1 if n= 1 n!= (n -1)! n if n > 1 function f (n: integer): integer; begin if n = 1 then f:= 1 else f:= n * f (n -1); (function f calls itself) end; 1 function f(n: integer): integer; begin if n = 1 then f:= 1 else f:= n * f (n -1); (function f calls itself"> 1 function f (n: integer): integer; begin if n = 1 then f:= 1 else f:= n * f (n -1); (function f calls itself) end;"> 1 function f (n: integer): integer; begin if n = 1 then f:= 1 else f:= n * f (n -1); (function f calls itself" title="Example 5. Compose a recursive function , which calculates the factorial of n as follows: n!= 1 if n= 1 n!= (n -1)! n if n > 1 function f (n: integer): integer; begin if n = 1 then f:= 1 else f:= n * f (n -1); (function f calls itself"> title="Example 5. Write a recursive function that calculates the factorial of a number n as follows: n! = 1 if n= 1 n!= (n -1)! n if n > 1 function f (n: integer): integer; begin if n = 1 then f:= 1 else f:= n * f (n -1); (function f calls itself"> !}




subroutines V TurboPascal


  • subroutine is a named, logically complete group of commands that can be called to be executed any number of times from different places programs.

Reasons for using subroutines

  • simplify the development of large programs by decomposing (dividing) the task into several subtasks;
  • greater visibility of the program;
  • saving memory.

Types of subprograms

procedures

functions

  • Procedure is an independent named part of the program designed to perform specific actions.

Procedures without parameters

  • Recording format :

procedure ;

end ;

  • All variables that are used in procedures without parameters are described in the main program (in the Var module).

Example . Write a program to find the volume of a cylinder.

program cylinder;

Var R, H, V: real;

Input Procedure ; (data entry procedure)

Writeln('Enter the radius value');

writeln('Enter height value');

procedure; { procedure calculations volume }

V:=PI*sqr(R)*H;

Output Procedure ; ( output procedure )

writeln('V=',V);


Procedures c parameters

  • Procedures can describe constants, variables, and other procedures.
  • The description section in procedures has the same structure as in the main program.
  • Local variables are variables declared within a procedure.
  • Local variables are not accessible outside of a procedure.
  • Changes to local variables within a procedure do not affect the values ​​of variables with the same name but declared outside the procedure.

Procedures c parameters

  • Global variables

Example .

program task;

Var a, b: integer;

procedurelocal;

Var a, x: char; For procedures local:

begin variable x - local variable

a:='! '; (the program cannot change its value)

b:=b+1; variable b - global variable

end ; (all changes to the value of this variable in the procedure

BEGIN are retained even after exiting the procedure)

b:=100; variable a in the main program whole type,

local; and in procedure - character type. variable a

writeln('a=', a); integer type is not available in the local procedure.

writeln('b=',b);

The result of the program execution: a=0; b=101.


); start; end ; "width="640"

Passing parameters to Turbo Pascal

  • 1. Passing parameters by value
  • Value parameters variables declared after the procedure name in parentheses. Before them there is no service word Var .
  • Recording format :

procedure (:

variable);

end ;


  • formal parameters .
  • actual parameters .

Example .

program parameter;

Var m, n: integer;

sum Procedure(a, b: integer);

writeln('S=',S);

summa(m,n); or summa(100,10);

Variables a And b are formal parameters, and variables m And n - actual. Actual parameter values m =100 and n =10 are passed to formal parameters a And b .

Changes to actual parameters occur only within the procedure and do not affect them outside the procedure.


; var variable:); start; end ; "width="640"

Passing parameters to Turbo Pascal

  • 2. Passing parameters by name
  • Variable parameters variables declared after the procedure name in parentheses and preceded by the service word Var .
  • Recording format :

procedure (:

variable; Var

variable:);

end ;



b then min:= b; if min c then min:= c; end ; BEGIN writeln('Enter three numbers'); readln(a1, b1, c1); writeln (' enter three numbers '); readln(a2,b2,c2); minimum(a1,b1,c1, min1); minimum(a2,b2,c2, min2); S:= min1 + min2; writeln('S=', S); END. Example. Given two triplets of numbers: a 1, b 1, c 1 and a 2, b 2, c 2. Find the value of the sum: S=min (a1, b1, c1) + min (a2, b2, c2) "width="640"

Var a1,b1,c1,a2,b2,c2, min1, min2, S: real;

Procedure minimum (a,b,c: real; Var min: real);

if min b then min:= b;

if min c then min:= c;

writeln('Enter three numbers');

readln(a1, b1, c1);

writeln (' enter three numbers ');

readln(a2,b2,c2);

minimum(a1,b1,c1, min1);

minimum(a2,b2,c2, min2);

S:= min1 + min2;

writeln('S=', S);

Example. Given two triplets of numbers: a 1, b 1, c 1 and a 2, b 2, c 2. Find the value of the sum: S=min (a1, b1, c1) + min (a2, b2, c2)


Function is a subroutine whose result is some value.

  • Recording format :

function (:

end ;

  • In the function body, the function name must be assigned the result of its execution.
  • When a function is called, its name with a list of actual parameters must be included in the expression as an operand.

program expression;

function module (a: real) : real;

writeln('Enter the value of the variable');

y:= modul(x-3) + modul(x+6);

writeln ('y=', y);

Example . Calculate the value of the expression: y = | x -3 | + | x+6 |

slide 1

slide 3

Subroutines: Global and Local Variables All subroutines must be declared in a declaration section. Each subroutine must have a name. Information between the main program and subroutines is transmitted by global parameters (variables) that are valid in any part of the program and have the name described in the main program. Inside the subroutine, local parameters (variables) can be used - their names and values ​​make sense only within the boundaries of the given subroutine and are not available to the calling program

slide 4

Formal and actual parameters In the description of subprograms, parameters are indicated only by names, therefore they are called formal. Until the subroutine is called, they have no meaning. They only reserve space for the actual parameters, fixing their number and data type. Actual parameter types: Value parameters indicate what value should be assigned to a particular subroutine parameter. After the subroutine ends, they return to their previous values, even if they were changed in the subroutine. The variable parameters in the subroutine take the place of the formal ones, they can change their value during the execution of the subroutine and save the changes when the subroutine exits (variable parameters are preceded by keyword Var).

slide 5

slide 6

Description of the procedure Program Pr1; Const...Type...Var...Procedure(); Description Begin Procedure body End; Begin ... (); …end. When the procedure is called, the formal parameters are replaced by the actual ones.

Slide 7

The procedure for calculating the sum of two numbers program pr1; Use crt; Var a,b,s:real; procedure summa(x,y:real;var z:real); beginz:=x+y; end; begin clrscr; writeln("Enter a,b"); readln(a,b); summa(a, b, s); writeln(" sum of numbers ",a:3:1," and ",b:3:1," = ",s:3:1); readln; end. x,y,z – formal parameters, local variables a,b,s– global variables a,b,s – actual parameters x y z a b s Parameter-values ​​Parameter-variable

Slide 8

Slide 9

slide 10

Calculate the value of the expression a:=(3n!+2m!)/(m+n)! What type of variables should be used to find the factorial? programpr2; Use crt; Varm,n,x,y,z:integer; a:real; procedure fact(d:integer;var q:integer); var i:integer; beginq:=1; for i:=1 to d do q:=q*i; end; begin clrscr; writeln("enter the values ​​n, m "); readln(n,m); fact(n, x); fact(m,y); fact(m+n,z); a:=(3*x+2*y)/z; writeln("value of expression when m= ",m:4," and n= ",n:4,"equals",a:8:3); readln; end. N!=1 2 3… N

slide 11

Input output of elements of a one-dimensional array The Random(X) function generates a random number from 0 to X of an integer or real type (before calling the function, it must be initialized using the Randomize procedure). If X is not specified, the result will be of type Real between 0.0 and 1.0. To get an array of integer random numbers from the range random(B-A+1)+A Task: Arrange the input of elements of a one-dimensional array using a random number generator (value range from -10 to 20) and the output of elements as a procedure. For A=-10 B=20 random(20-(-10)+1)+(-10)

slide 12

slide 13

slide 14

Description of the function Functions are designed to calculate only one value, 1. therefore, its first difference is that the procedure can have new values ​​for several parameters, and the function has only one (it will be the result). 2. The second difference is in the function header. It consists of the word FUNCTION followed by the name of the function, followed by a list of formal parameters in parentheses, followed by the type of the function result separated by a colon. 3. The function body must contain at least one assignment operator, where the function name is on the left side, and its value is on the right side. Function (): Description Begin Function body:=; end;

slide 15

Calculate the value of the expression a:=(3n!+2m!)/(m+n)! program fn2; Use crt; Varm,n:integer; a:real; function fact(d:integer) :longint; var i:integer; q:longint; beginq:=1; for i:=1 to d do q:=q*i; fact:=q; end; begin clrscr; writeln("enter the values ​​n, m"); readln(n,m); a:=(3*fact(n)+2*fact(m))/fact(m+n);; writeln("value of expression when m= ",m:4," and n= ",n:4,"equals",a:8:3); readln; end.

slide 16

Write a program that will find ab, that is b-th degree numbers A, where A and B are integers and B>0, entered from the keyboard. Write a program, replacing the function with the procedure program pr2; Use crt; var a,b:integer; c:longint; Function steps(x,y:integer):longint; var i:integer; s:longint; begin s:=1; for i:=1 to y do s:=s*x; Stephen:=s; end; begin clrscr; writeln("Enter values ​​a, b"); readln(a,b); C:=step(a,b); writeln("s=",s); readln; end.

slide 17

slide 18

Mechanism for passing parameters to functions and procedures What will be printed by the procedure and what by the program? Global variables Local variables a b 3 3 -3 Address c a b c 48 Address c A:=b+3 B:=3*a C:=a+b State C 24 5 8 Answer

slide 19