Procedures and functions in Pascal. Recursion. Subroutines Often a task requires you to repeat a certain sequence of statements in different parts of the program. Procedures and functions Procedures and functions presentation

Recursion in Pascal Teacher: Tlekhurai Yu.V. Municipal educational institution "Lyceum No. 8" What do you see in the paintings? This phenomenon in art is called recursion “To understand recursion, you must first understand recursion.” recursion - partial definition of an object through itself, definition of an object using previously defined ones. Scientifically speaking: Recursion - a method of defining a class of objects or methods by first specifying one or more (usually simple) of its basic cases or methods, and then specifying on their basis the rules for constructing the class being defined. Peter Deutsch Peter Deutsch

Human iteration.

Recursion is from God.

Recursion in physics Recursion in language and literature A classic example of infinite recursion is two mirrors placed opposite each other: two corridors are formed in them from fading reflections of mirrors. Another example of infinite recursion is self-excitation effect (positive feedback) y electronic circuits gain, when the signal from the output reaches the input, is amplified, again reaches the input of the circuit and is amplified again. Amplifiers for which this operating mode is standard are called self-oscillators. An example of a recursive dictionary entry: “The priest had a dog...” - typical recursion Several stories by Stanislaw Lem are devoted to incidents with infinite recursion: A story about sepulcs (“The Star Diaries of John the Quiet”), in which the hero successively moves from an article about sepulcs to an article about sepullation , from there to an article about sepulcaria, which again contains a reference to the article “sepulcaria”. A story about an intelligent machine that had enough intelligence and laziness to build a similar one to solve a given problem, and entrust the solution to it (the result was an infinite recursion, when each new car built one similar to herself and handed over the task to her). Recursion in programming is a way of organizing a computational process in which a procedure or function refers to itself during the execution of its constituent operators. In order for such a call not to be endless, the text of the subroutine must contain a condition upon reaching which no further call occurs. thus, a recursive call can only be included in one of the branches of the subroutine. Example. Calculating the factorial of a natural number Create a recursive function that calculates the factorial of the number n as follows: function f (n: integer): longint; begin if n = 1 then f:= 1 else f:= n * f(n -1); (function f calls itself) end Pascal program using recursion: Var n: integer; a: longint; function factorial (n: integer): longint; begin if n = 1 then factorial:= 1 else factorial:= n * factorial (n -1); End; Begin Write(‘n=’); Readln(n); A:= factorial(n); Write(‘n!=’,a); Readln; end. Leonardo of Pisa Fibonacci

Fibonacci numbers are elements of a number sequence

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ..., in which each subsequent number is equal to the sum of the two previous ones.

Task: Display a series of Fibonacci numbers consisting of n elements. Description of variables: n – number of elements of the series; a, b – values ​​of the last two elements of the series; c – buffer (“spare”) variable; i – counter. Algorithm for solving the problem: 1. Get the value of n. 2. Assign a and b the values ​​0 and 1 respectively (these are the first numbers of the Fibonacci series). Display them on the screen. 3. Starting from the 3rd element to n: a) display the sum of a and b, b) store the value of variable b in c, c) write the sum of a and b to b, d) assign a the value of c. Pascal program using iteration: program Fibonacci; var a,b,c,i,n: integer; begin write("n = "); readln(n); a:= 0; write(a," "); b:= 1; write(b," "); for i:=3 to n do begin write(a+b," "); c:= b; b:= a + b; a:=c; end; readln; end. Pascal program using recursion: The recursive definition for calculating Fibonacci numbers is as follows: This definition of Fibonacci numbers can easily be converted into a recursive function: function f(n: Integer) : longint; begin If n<= 1 Then f:= n else f:= f(n– 1) + f(n - 2); end; Program chislaFibonacci; var n,i: integer; a: longint; function fib (n: integer): longint; begin If n <= 1 Then fib:= n else fib:= fib(n– 1) + fib(n - 2); End; begin write(‘n=’); readln(n); for i:=0 to n do begin A:= fib (n); write (‘ ’,a); end; readln; end. Домашнее задание Написать программу нахождения НОД двух натуральных чисел, используя алгоритм Евклида и рекурсию Даны два натуральных числа A And b. If A= b, then node ( A,b)=a. If A>b, then node ( A,b)= node ( a -b,b). If A< b, then node ( A,b)= node ( A,b-a). Program noddvyxchisel; var a,b: longint; function nod(a,b:longint): longint; begin If a = b Then nod:= a else if a>b then nod:= nod(a-b,b) else nod:= nod(a,b-a) End; begin write('a='); readln(a); write('b='); readln(b); A:= nod(a,b); write(‘nod=’,a); readln; end. Problem about the Towers of Hanoi. In this case, the following rules must be strictly observed:

  • You can only move one disk at a time;
  • a larger disk cannot be placed on smaller disk;
  • the removed disk must be put on any pin before the other disk is removed.
  • Hardworking Buddhist monks carry discs from spire to spire day and night. Legend claims that when the monks finish their work, the end of the world will come. One could calculate that solving a problem with 64 disks would require 264–1 moves. Therefore, as for the end of the world, it will occur after five billion centuries, if we consider that one disk moves in one second. However, both the problem and the legend for it were invented in 1883 by the mathematician Edouard Lucas from the College of Saint-Louis.

One of the three diamond spiers bears 64 round gold discs. The discs have different radii and are located on the spire in descending order of radii from base to top. It is necessary to transfer the disks from the first spire to the second, using the third spire if necessary.

Task. Create a recursive program that would solve the problem posed above about the Towers of Hanoi with the number of disks equal to n (n = 1, 2, ...). Solution. Let's enter names for the spiers: a, b, c. Let hanoi(n,a,b,c)- the required function that returns the sequence of movements of disks with a on b using c according to the rules described above. When n=1 we know how to solve the problem. You just need to perform the “move” operation a on b" Let's assume that we can solve this problem for n – 1 disks. Move n–1 disks from a on With. Next, move the one remaining disk from a on b and finally move n–1 disks from c on b. Input data: number of discs on peg a; Output: sequencing; Step0:(define variable type); Step1: (description of the hanoi procedure, which displays the sequence of actions); Step1.1:(move (n-1) disks from peg a to peg b); Step1.2:(move the nth disk from a to c); Step1.3:(move (n-1) disk from b to c); (steps 1.2-1.3 are performed recursively); Step2:(main program); Step2.1:(enter the number of disks); Step2.2: (calling the hanoi procedure). Solving the problem in Pascal Program bahnya; var n: integer; a,b,c: char; procedure hanoi(n: integer;a,b,c: char); begin if n>0 then begin hanoi(n-1,a,c,b); writeln ("Peremestit disk so sterzhnya ",a," na sterzhen" ",b); hanoi(n-1,c,b,a); end; end; Begin write ("Vvedite naturalnoe chislo n"); readln ( n); a:="a"; b:="b"; c:="c"; hanoi (n,a,c,b); readln; end. Homework Write a program for calculating the degree with a natural exponent Given: degree base X Exponent To If k=0, then degree(k,x)=1, Otherwise degree(k,x)= x· degree(k-1,x) Program stepen; var y: real; n:integer; function step(k:integer, x:real): real; begin If k = 0 Then step:= 1 else step:= x * step(k-1,x) End; begin write(‘vvedite osnovanie stepeni x=’); readln(y); write(‘vvedite pokazatel stepeni k=’); Readln(n); write(‘x v stepeni k=’,step(n,y)); readln; end. Independent work

  • Find the sum of the digits of a number
  • Determine whether a given natural number is prime
  • Find the first digit of a number
  • Convert natural number from decimal s.s. to binary
  • Find the sum of the elements of an integer array consisting of 20 elements
  • Swap the values ​​of two integers
  • Order the values ​​of three variables a, b, c in ascending order
  • Find the number of digits in natural number n
  • Find the largest of three given numbers
  • Find the number of positive numbers among four A, B, C, D
Answers for independent work No. 2 Program simple; var n, m, s: integer; function prost(m, n:integer): boolean; begin If n = m Then prost:= true else prost:= (n mod m<>0) and prost (m+1, n); End; begin write('n='); Readln(n); M:=2; If prost(m,n) then write (n,’prostoechislo’) Else write (n,’sostavnoe’); readln; end.

program translation;

procedure dvd(n:longint);

If n >1 Then dvd (n div 2);

write(n mod 2);

Subroutines Often a task requires you 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, programming languages ​​use subroutines. A subroutine is a specially designed block of a program for its subsequent repeated use 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 problems that greatly facilitate programming: 1. they eliminate the need to repeatedly repeat similar fragments in the program text, i.e. reduce the size of the program; 2. will improve the structure of the program, making it easier to understand when parsing; 3.reduce the likelihood of errors, increase resistance to programming errors and unforeseen consequences during modification.


Procedures and functions There are two types of subroutines in Pascal: procedure (PROCEDURE) and function (FUNCTION). Procedures and functions in Pascal are declared in the declaration section behind the variable section. ProgramProgramName; VAR ... // section for describing variables of the main program; procedure ProcedureName; var ... begin ...//Procedure body end; begin //body of the main program 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 correspond to the formal ones in quantity, order and type.




Procedures Procedures are used when a subroutine needs to obtain multiple results. There are two types of procedures in Pascal: procedures with parameters and without parameters. A procedure is accessed by the procedure name, which can be 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 operator of the calling program after the procedure is called.


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


Example 2. Create a program for swapping two numbers c=5 and d=7 program obmenDan; var c,d:integer; procedure exchange (a,b:integer); var m:integer; begin m:=a; a:=b; b:=m; writeln(a,b); end; begin writeln("Enter 2 numbers: "); readln(c,d); exchange(c,d); writeln(c," ",d); end. c5 d 7 a 5 b 7 1) when calling the obmen procedure with two parameters 5 and 7, the same numbers 5 and 7 are placed in variables a and b, respectively: 2) then in the procedure the values ​​of memory cells a and b are rearranged: c5 d 7 a 7 b 5 3) but in variables c and d the data has not changed, because they are in other memory cells


In order for 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 formal parameters, it is necessary to add the word VAR before the required variables: procedure exchange (var a,b:integer); с5 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); (call procedure work) writeln ("Summa elementov = ",sum); writeln("Srednearifmeticheskoe = ",sr:4:1); end; end.


Result of the program: 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 enters array elements, calculates the sum and average. The variables s and s1 are returned to the main program, so the service word var is placed before their description. 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 the Pascal language 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. A function is accessed on the right side of the assignment operator, indicating the function name and 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; var y: real; ( local variables) begin y:= exp (x * ln (a)) ; stp:= y;(assigning a function name to the result of subroutine calculations) end; (function description complete) begin d:= stp (2.4, 5); (calculating powers of different 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 structure and provided with a name (an independent program block), for solving individual problems. Description of the procedure: procedure () (section for executing local names) Begin (section for executing operators) End; Function description: function (): type; (section for describing local names) Begin (section for executable statements) := ; (required parameter) End; Procedure call: (); Function call: := (); 1. On the right side of the assignment operator. 2. In the 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 property of recursiveness. A recursive function must necessarily contain a condition for ending recursivity 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. Create a recursive function that calculates the factorial of the 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" class="link_thumb"> 19 !} Example 5. Create a recursive function that calculates the factorial of the 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. Create a recursive function that calculates the factorial of the 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"> title="Example 5. Create a recursive function that calculates the factorial of the 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"> !}



Slide 1

Slide 3

Subroutines: global and local variables All subroutines must be described in the description section. Each subroutine must have a name. Information between the main program and subroutines is transmitted by global parameters (variables) that operate in any part of the program and have a name described in the main program. Local parameters (variables) can be used inside a subroutine - their names and values ​​have meaning only within the boundaries of a given subroutine and are not available to the calling program

Slide 4

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

Slide 5

Slide 6

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

Slide 7

The procedure for calculating the sum of two numbers program pr1; Usescrt; Var a,b,s:real; procedure summa(x,y:real;var z:real); begin z:=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 Value parameters Parameter variable

Slide 8

Slide 9

Slide 10

Calculate the value of the expression a:=(3n!+2m!)/(m+n)! To find the factorial, what type of variables is appropriate to use? program pr2; Usescrt; Var m,n,x,y,z:integer; a:real; procedure fact(d:integer;var q:integer); var i:integer; begin q:=1; for i:=1 to d do q:=q*i; end; begin clrscr; writeln("enter values ​​n, m"); readln(n,m); fact(n,x); fact(m,y); fact(m+n,z); a:=(3*x+2*y)/z; writeln("the value of the expression with m= ",m:4," and n= ",n:4,"is equal to",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 the X parameter is not specified, the result will be of type Real in the range from 0.0 to 1.0. To obtain an array of random integer numbers from the range random(B-A+1)+A Task: Formulate 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, but the function has only one (it will be the result). 2. The second difference is in the function title. It consists of the word FUNCTION, followed by the name of the function, then a list of formal parameters in parentheses, followed by the type of the function's 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 (): Descriptive Begin Function body:=; End;

Slide 15

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

Slide 16

Create a program that will find ab, that is, the bth power of the number A, where A and B are integers and B>0, entered from the keyboard. Compose a program by replacing the function with the procedure program pr2; Usescrt; Var a,b:integer; c:longint; Function stepen(x,y:integer):longint; var i:integer; s:longint; begin s:=1; for i:=1 to y do s:=s*x; step:=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 Reply

Slide 19

8th grade. Programming in ABC Pascal

Informatics teacher of the NIS of Uralsk Physics and Mathematics Zelenov Boris Aleksandrovich


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

  • Develop a concept of procedures and functions in a programming language.

  • Students know the concepts of “procedures” and “functions”, determine formal and actual parameters

Expected Results - Descriptors:

1.Knows the definition of “procedure”

2.Knows the definition of “function”

3.Determines actual and formal parameters

4.Differentiates between value and variable parameters

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



Elvira's standard plan

1. Remove papers

2. Water the flowers

3. Wash the desks

4. Wipe the glass

End of the algorithm

How to improve the organization of this process?




Lesson topic

Subroutines:


Ishki bagdarlama

Subroutine

Procedure

Procedure

Parameterler

Useful phrases:

To pass variable values ​​to a procedure (function), actual parameters are used...

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


The concept of a subroutine

Definition

Subroutine- This is a separate functionally independent part of the program.

Subroutines

Procedures


  • eliminate the need to repeatedly repeat similar fragments in the program text;
  • 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 perform the algorithm for drawing one fragment (picket fence), and then constantly refer to this procedure, changing the initial position of the pen


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

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

Interaction between the main program and the subroutine



Block diagram

  • Subroutine (procedure or function) call block

Subroutine (procedure or function) name


Block diagram


The description of the procedure is as follows:

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


The function description looks like:

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

descriptions 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 executing the operators that form the body of the function is always a single value, so calling a function can be used in appropriate expressions along with variables and constants.

Procedures

Functions

Can have multiple results or perform some action

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

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

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

The procedure call command is a separate command that can be used independently

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

The function body must contain at least one assignment operator with the function name on the left side.


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 subroutine
  • Specified in the subroutine

The procedure is called by an operator having the following format:

procedure name(list of actual parameters);

  • List of actual parameters- this is a listing of them 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 parameters-values, passed by reference - parameters-variables. The latter differ in that in the procedure (function) header they are preceded by the service word var.

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

Procedure Name (a, b: integer);

Main program

When changing these values ​​during the execution of a procedure (function), the original data (actual parameters) cannot change


Var c, d: integer;

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

Procedure

Procedure Name (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, their corresponding actual parameters 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. Accessing a 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 general cleaning in the classroom: remove papers, water flowers, wash desks, wipe glass. How can she better organize her work? Help Elvira.


Elvira's Advanced Plan

Subroutines:

Arsen - puts away the papers

Mila - watering flowers

Vitaly – washes desks

Indira – wiping the glass

1. Execute Arsen

2. Run Mila

3. Execute Vitaly

4. Run Indira

End of the algorithm


  • What new programming language structures 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 you can use procedures or functions.

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

Let's meet

next lesson!

The purpose of the lesson

educational

  • to form among students a unified system of concepts related to the concepts of procedure and function;
  • teach how to use subroutines in solving problems in Pascal, and also teach to understand what type of subroutine is needed when solving a certain problem;
  • show basic techniques for using subroutines;

educational

  • cultivate accuracy, attention, organization;
  • culture of computing skills;

developing

  • develop logical thinking, algorithmic culture of students;
  • develop knowledge and skills to compose and debug subroutines in Pascal.

Students must:

  • know the rules for writing procedures without parameters and with parameters;
  • know the rules for writing functions;
  • be able to apply procedures and functions to solve simple problems.

During the classes

I. Org. moment

II. Introduction. Relevance

Give out the task on pieces of paper ( Annex 1 ). Find repetitions.

Sometimes in different places of the program you have to perform almost the same sequences of actions with different initial data. Such sequences of actions can be formalized in the form of so-called subroutines (from English, subroutine) – group operators into a block that can be accessed by name and repeatedly.

Subroutines shorten the text of a program, significantly reduce their execution time, and make life easier for programmers who can create programs modularly, that is, by assembling a complex program from completed pieces of simpler components. This allows a group of programmers to create large programs, and a group of schoolchildren to develop and implement any global projects

Subroutines are divided into procedures and functions.

Built-in (standard) procedures and functions are part language and can be called by name without prior description. For example , abs, sqrt, ln, sin... are functions (return a result), readln, write... are procedures (do not return a result). Their presence greatly facilitates the development of application programs. However, in most cases some specific for a given program, the actions do not find direct analogues in the Turbo Pascal libraries, and then the programmer has to develop his own non-standard procedures and functions.

III. Explanation of new material

User procedures are written ourselves programmer in accordance with the syntax of the language in subroutine description section.

The structure of the procedure follows the structure of the program; it is a “program in miniature” - it is also represented by a header and a body.

The header consists of the reserved word procedure, the identifier (name) procedures.

VAR ... // section for describing variables of the main program

procedure ProcedureName;

//body of the main program

The procedure call for subsequent execution is recorded in the body of the main program.

Example 1. Program for calculating area and perimeter.

Advantages of subroutines:

  • Programs written using subroutines easier to test and debug, they have a clearer logical structure.
  • The independent nature of subroutines allows their creation to be entrusted to various programmers. This way, the programming work is divided and, thus, its completion is accelerated;
  • Using subroutines saves memory. Memory for storing variables used in a subroutine is allocated only for the duration of its operation and is released as soon as its execution ends.

Example 2. The user enters two sides of three rectangles. Derive their areas.

You can solve the problem like this:

for i:=1 to 3 do

writeln('Enter a and b:');

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

It is considered good programming style to use procedures. A procedure is needed that will calculate the area of ​​a rectangle. Here's what the main program will look like schematically:

calculation

calculation

calculation

The text procedure already exists (see example 1). Let's create a second procedure that calculates the area. But in order to calculate S, you need to know 2 sides, so the procedure needs to show which sides it should multiply.

procedure pl (c,d: integer);

writeln(‘area of ​​a rectangle with sides ’,c, ‘ ‘ ,d, ‘=‘,S);

A parameter is a variable that is assigned a value. Exist formal parameters , defined in the subroutine header, and actual parameters – expressions that specify specific values ​​when accessing a subroutine.

The procedure will be executed if you call it by name and specify the actual parameters , separated by commas and enclosed in parentheses:

The actual parameters must match the formal ones in type and quantity.

So, the main program:

for i:=1 to 3 do

Comment. When solving this problem, it is necessary to check the numbers entered by the user (they must not be negative, otherwise the program will be interrupted).

Let's create a verification procedure:

procedure error (f,g:integer);

if (f<0) or (g<0) then begin

writeln('the sides of a rectangle cannot be negative');

halt; // program interruption

Final program – Appendix 4

So the format of the procedure:

Procedure<имя>(formal parameters);

<операторы>;

Example 3. Write a program for swapping the places of two numbers c=5 and d=7.

program exchangeDan;

var c,d:integer;

procedure exchange (a,b:integer);

m:=a; a:=b; b:=m;

writeln("Enter 2 numbers: ");

writeln(c," ",d);

After starting the program, you can see that the formal parameters (in the procedure) have changed places, but the actual ones (which are used in the main program) have not changed. Let's look at the figure that shows part of the RAM:

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:

3) but in variables c and d the data has not changed, because they are in other memory cells.

In order for variables c and d, a and b referenced the same memory cells (if the values ​​of a and b change, then the values ​​of c, d will also change) when describing formal parameters, it is necessary to add the word VAR before the required variables:

procedure exchange (var a,b:integer);

Change the obmenDan program:

Error due to var. Numbers are constants that cannot be changed in a procedure.

Example 4. Find the area of ​​a circle using a procedure that only calculates but does not display the result on the screen.

procedure circle(r:real);

The procedure should return the result:

procedure circle (r:real; var S:real);

readln(a, e);

Comment: The variable in procedure S is used to return the results of the procedure to the main program. When it changes, the actual parameter in the calling program also changes, i.e. variable e.

More often, for this in Pascal, instead of procedures, functions (subroutines that return something) are used.

The function is similar to the procedure, but there are two differences.

  • The function transmits the result of its work to the program - a single value, the carrier of which is the name of its function.
  • The function name can appear in an expression as an operand. The function returns the result to the point of its call.

For example, sqr(x) – will square the value x and return the calculated value of the square of the number x to the call point: y:=sqr(x);

A user-defined function consists of a function header and a function body. The body of the function is similar in structure to the program. Description of labels, constants, types, etc. valid only within the scope of this procedure.

Function<имя>(formal parameters):<тип результата>;

<операторы>;

The statement section must contain at least one statement that assigns a value to the function name. The result of the last assignment is returned to the call point.

Example 5. Let's rework the problem about the area of ​​a circle.

function circle (r:real): real;

a:=circle(5); (MUST be assigned)

Example 6. Find 1!+2!+…+n!

We use the function of finding the factorial, because we feed it as an input and get the result.

function fact (a:integer): integer;

for i:=1 to do

In the line fact:=fact*I;

the compiler will find an error, because fact must be called with parameters. Therefore, an additional variable is usually introduced into which the result is placed. And then this result is assigned to the fact variable:

program factorial;

var sum,n,j: integer;

function fact (a: integer): integer;

var i,d: integer;

for i:=1 to do

for j:=1 to n do

sum:=sum+fact(j);

IV. Lesson summary

At this time, the programming process turns into industrial software production based programming technologies. Most experts are of the opinion that top-down program design method most suitable for solving complex problems. First, the task is defined in general terms, then its structure is gradually clarified. At the next step, each subtask, in turn, is divided into a number of others. The solution to a separate fragment of a complex problem is an independent program block - a subroutine.

V. Homework

Solve problems (in writing):

  1. Create a procedure that replaces all the letters a in the entered string with *.
  2. Two proposals are given. Find the total number of letters “n” in them. (Define a function to calculate the number of letters “n” in a sentence.)