Contacts

Procedures and functions in pascal presentation of the Poles. Procedures and functions. Reasons for using routines

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

To use presentation previews, create a Google account and log in to it: https://accounts.google.com


Slide captions:

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

A subroutine is an autonomous part of a program that performs a specific algorithm and can be accessed from various parts of the general program. The use of 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 declaration 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 correspond to the formal ones in quantity, order and type.

The subroutine also has variables. with whom she later works. They are again divided into two types: 1) Global variables, that is, those that act throughout the entire program 2) Local ones - those that act only in a procedure or function

Procedures They are used in cases where it is necessary to obtain several results in a subprogram. There are two types of procedures: with a parameter; without parameter.

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

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

Procedure with a parameter. 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.

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: c 5 d 7 a 5 b 7

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); c 5 d 7 a b

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

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

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

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.

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.

Create a recursive function that 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) end ;

Tasks Change the values ​​of the 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.


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 the 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!

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, 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 endless recursion, when each new machine built a similar one and delegated the task to it).

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; 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. begin 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; write("n = "); readln(n); a:= 0; write(a," "); b:= 1; write(b," "); for i:=3 to n do begin write(a+b," "); c:= b;<= 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. Домашнее задание Написать программу нахождения НОД двух натуральных чисел, используя алгоритм Евклида и рекурсию Даны два натуральных числа b:= a + b; a:=c; end; readln; b:= a + b;= end. Pascal program using recursion: b:= a + b;,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; readln; b:= a + b;>end. Pascal program using recursion: b:= a + b;,begin If n A And,b. readln; b:= a + b;< end. Pascal program using recursion: b:= a + b;,begin If n A b:= a + b;,If b,

  • then node (
  • b)=a.
  • b)=
  • node (

a -b

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 - the required function that returns the sequence of movements of disks with a on according to the rules described above. When n=1 we know how to solve the problem. You just need to perform the “move” operation - the required function that returns the sequence of movements of disks with a " Let's assume that we can solve this problem for n – 1 disks. Move n–1 disks from With - the required function that returns the sequence of movements of disks with a on. Next, move the one remaining disk from using and finally move n–1 disks from on. on 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:="c"; hanoi (n,a,c,b); homework Write a program for calculating the degree degree base
  • 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=');