Procedures - PowerPoint PPT Presentation

1 / 65
About This Presentation
Title:

Procedures

Description:

Procedure and Function are the two kinds of subprograms in Pascal. ... Procedure ... refers to the symbol table to check that the identifier is being used correctly. ... – PowerPoint PPT presentation

Number of Views:23
Avg rating:3.0/5.0
Slides: 66
Provided by: cemc2Math
Category:
Tags: procedures

less

Transcript and Presenter's Notes

Title: Procedures


1
Procedures Functions
  • By Lixin Luo
  • Reference Carter, J. (1989). Problem solving in
    Pascal. Don Mills, Ont. Addison-Wesley

2
Procedures Functions
  • Procedures - Section 1
  • Introduction

3
Modular Programming
  • Example Making a dish
  • Wash the raw materials
  • Cut the raw materials
  • Cook them
  • It refers to a process that the programmer breaks
    a complex problem up into manageable subproblems,
    solve each of these, and then put the pieces
    together to get the solution for the full
    program.

4
Subprograms
  • Procedure and Function are the two kinds of
    subprograms in Pascal.
  • Predefined procedures read, readln, write,
    writeln
  • Predefined functions sqr, chr, copy

5
Procedure
  • Suppose you have been asked to write a program
    that handles the accounting for the student
    association at Western. The programs output will
    consist of a number of pages, each of which
    should have a heading of the form
  • Student Association
  • Western School

6
An Example of a Procedure
  • Procedure PrintHeading
  • Const
  • Centre 40 half page width
  • Begin
  • page
  • writeln ( Centre 8, Student
    Association)
  • writeln ( Centre 6, Western School)
  • End

7
  • Program Sample
  • Var
  • .
  • Procedure PrintHeading
  • Const
  • .
  • Begin
  • .
  • End
  • Begin main program
  • .
  • PrintHeading
  • .
  • PrintHeading
  • .
  • End. main program

8
The differences between a procedure and a program
  • The word procedure is used instead of program
  • A semi-colon is used to terminate the procedure.

9
Procedures Functions
  • Procedures - Section 2
  • Local Global Identifiers

10
Local Global Identifiers
  • Scope
  • The scope of an identifier is the parts of a
    program for which an identifier is valid.
  • Local Vs Global
  • e.g., local and global variable
  • Local variable a variable that is declared in a
    subprogram. It can only be used in the subprogram
    body and has the local scope of this subprogram.
  • Global variable A variable that is declared in
    the main program. It can be used within any
    procedure or function.

11
Syntax diagram
  • For a ltprogramgt is
  • Program
  • For a ltprocedure definitiongt is
  • Procedure definition

program heading
procedure heading
12
Any identifiers defined in program A are global
to procedures B, C, and D.
  • Program A
  • Procedure B
  • Procedure C
  • Procedure D

Any identifiers defined in procedure B are local
to B.
Any identifiers defined in procedure C are local
to C, but global to D.
Any identifiers defined in procedure D are local
to D.
13
Local Global Identifiers
  • Identifiers that are local to a block only
    exist while that block is being executed. They
    have no meaning outside of that block. In other
    words, the rest of the program cannot see them.
  • Each time that a block is entered, any local
    variables must be reinitialized and each time
    that a block is existed, local variables lose any
    values that they may have been given.

14
  • Program Ex2
  • var
  • A integer
  • Procedure P
  • var
  • B integer
  • Begin
  • B A
  • A A 1
  • writeln (The value of B is , B1)
  • End P
  • Begin main program
  • A 0
  • P
  • writeln (The value of A is , A1)
  • End.

The output of the program The value of B is
0 The value of A is 1
15
What happens if both a local and a global
identifiers are the same?
  • The global and local variables having the same
    identifiers do not interfere with each other.
  • The definition of the local identifier takes
    precedence and the global identifier has no
    meaning within the block containing the local
    identifier.

16
  • Program Ex3
  • var
  • A integer
  • Procedure P
  • var
  • A integer
  • Begin
  • A 0
  • writeln (The value of A is , A1)
  • End P
  • Begin main program
  • A 1
  • writeln (The value of A is , A1)
  • P
  • writeln (The value of A is , A1)
  • End.

The output of the program The value of A is
1 The value of A is 0 The value of A is 1
17
Procedures Functions
  • Procedures - Section 3
  • Value Parameters

18
This procedure finds and writes the
minimum value of the global integer variables
A, B, and C.
  • Procedure WriteMinABC
  • var
  • Minimum integer
  • Begin
  • if A lt B
  • then B excluded
  • if A lt C
  • then
  • Minimum A
  • else
  • Minimum C
  • else A excluded
  • if B lt C
  • then
  • Minimum B
  • else
  • Minimum C
  • writeln (Minimum value is , Minimum1)
  • End

Problems . Not useable if we want to find the
minimum value of the variables with different
names, such as X, Y,and Z. . Not portable from
one program to another
19
Using Parameters in a Procedure
  • Procedure WriteMin (A integer B integer C
    integer)
  • var
  • Minimum integer
  • Begin
  • if A lt B
  • .
  • as in the last example
  • .
  • End

Parameter list it serves a declaration of A,
B, and C as the parameters of the
procedure. Parameters are local to the
procedure.
20
To call a procedure with parameters
  • To find and write the minimum value of the global
    variables A, B, and C
  • WriteMin (A, B, C)

To find and write the minimum value of the global
variables X, Y, and Z WriteMin (X, Y,
Z)
The variables A, B, and C (or X, Y, and Z) in
the call of WriteMin are called arguments.
21
The passing of values
  • When a procedure like WriteMin is called, the
    names of the arguments are completely ignored by
    the procedure. Instead, the values of the
    arguments at the time of the call are
    automatically assigned to the parameters of the
    procedure. We refer to this automatic transfer of
    values, from arguments to parameters, as a
    passing of values.
  • The order in which the parameters are written
    determines which argument value gets assigned to
    which parameter.

22
  • Program Sample
  • var
  • X, Y, Z integer
  • Procedure WriteMin (A integer B integer C
    integer)
  • Begin
  • .
  • End
  • Begin main program
  • X 7
  • Y 4
  • Z 0
  • WriteMin (X, Y, Z)
  • .
  • End. main program

23
The arguments of a procedure can be any
expressions whose values are of the appropriate
value. They dont need to be single identifiers.
  • Program Sample
  • var
  • A, I integer
  • Procedure WriteMin (A integer B integer C
    integer)
  • Begin
  • .
  • End
  • Begin main program
  • A 7
  • I 4
  • WriteMin (A3, I 2, 6)
  • .
  • End. main program

24
  • Before the call to WriteMin, the variables in the
    main program have values, but the parameters in
    procedure WriteMin have no values.
  • Main Program procedure WriteMin
  • A A
  • I B
  • C

At the time of the call, the arguments are
evaluated A3 I 2 6
10 8 6
The values of the arguments are then given to
the parameters Main Program procedure
WriteMin A A I B
C
25
Parameters need not all be of the same type.
  • Example
  • A procedure WritePower is to find and write
    values of expressions of the form
  • Where Base is real and Exponent is integer. A
    suitable heading for this procedure would be
  • Procedure WritePower (Base real Exponent
    integer)

WritePower (3.0, 2) WritePower (3, 2)
The argument for Base can be either real or
integer because Pascal allows us to assign an
integer value to a real variable the value for
Exponent must be integer.
26
Procedures Functions
  • Procedures - Section 4
  • Variable Parameters

27
  • Problem
  • Information can be passed to the procedure from
    the calling block but it cannot be sent back.

Solutions . Using global variables . Using
variable parameters
The benefit of using variable parameters .
They allow two-way communication between programs
and subprograms while still retaining the
flexibility and portability afforded by
parameters.
28
This program demonstrates the use of a
variable parameter
  • Program Ex1
  • var
  • A integer
  • Procedure Change ( var B integer)
  • Begin
  • if B gt 0
  • then
  • B 1
  • else
  • B 0
  • end
  • Begin
  • A 5
  • writeln ( The value of A is now , A1)
  • Change (A)
  • writeln ( The value of A is now , A1)
  • End.

Output The value of A is now 5 The value of
A is now 1
29
Call by reference
  • The effect of creating a variable parameter is to
    make any reference to the parameter in the
    procedure act as a reference to the corresponding
    argument.
  • For example
  • If we assign a new value to the parameter, that
    value will be assigned to the corresponding
    argument.
  • Because each use of a variable parameter causes a
    reference to the corresponding argument, a call
    using a variable parameter is sometimes known as
    a call by reference.

30
About the form of the arguments
  • Because a change to a variable parameter causes a
    change to the corresponding argument, the
    argument must be a variable.
  • Q Can we have an element of an array as an
    argument?
  • The argument and the parameter must be of exactly
    the same type.
  • Q Can we have an integer argument passed to a
    real variable parameter?

31
Value Parameters vs. Variable
Parameters
In a call with a value parameter, the value of
the argument is determined at the time of the
call and this value is assigned to the parameter

In a call with a variable parameter, any
reference to the parameter causes a reference
to the argument.
The argument must be a variable.
The argument can be a variable, constant, or
other expression.
  • Values can be passed two ways from the calling
    block to the the procedure and back to the
    calling block.

Values can be passed one way from the calling
block to the procedure.
32
Value Parameters vs. Variable
Parameters
  • Use value parameters whenever possible. It can
    minimize the risk of accidentally changing some
    variables in the calling block.
  • Normally use variable parameter only if the
    procedure must send values back to the calling
    block.

It is common to use both value parameters and
variable parameters in one parameter list.
33
This program demonstrates the use of value and
variable parameters together
  • Program Ex2
  • var
  • SalesTax, Total real
  • Procedure ProcessSale ( BasePrice real
    TaxRate real var Tax real var FinalPrice
    real)
  • Begin
  • Tax BasePrice TaxRate
  • FinalPrice BasePrice Tax
  • end
  • Begin
  • ProcessSale (20.00, 0.07, SalesTax, Total)
  • writeln ( Sales Tax , SalesTax102)
  • writeln (Total Price , Total102)
  • End.

When ProcessSale is called Main Program
procedure SalesTax Tax


After ProcessSale has been executed Main Program
procedure SalesTax Tax

Output Sales Tax 1.40 Total Price
21.40
34
Procedures Functions
  • Procedures - Section 5
  • Structured Parameters More Details

35
Parameter types
  • Parameter types can be any valid type, including
    arrays and other user-defined types. The only
    restriction is that, whatever the type, it must
    be specified in the parameter list of the
    procedure by a lttype identifiergt -- a single
    word.

Example Procedure BadExample (Name array
1..20 of char)
This procedure heading is not valid because the
type specification of Name is not a single
identifier.
36
Parameter types
  • By creating an appropriate user-defined type in
    the main program and then ensuring that both the
    arguments and parameters are of this type, - we
    can fool the complier ! we can use parameters
    of any valid type.

Example Program OK type String array
1..20 of char . Procedure GoodExample
(Name String) .
37
Syntax diagram
  • Procedure definition
  • Procedure heading
  • Parameter list

38
Write a parameter list in a concise form
  • Example 1
  • (First real Second real Third real Fourth
    integer)
  • -gtgt (First, Second, Third, real Fourth integer)
  • Example 2
  • (Var First, Second real Third real)

39
The order in which the procedures are defined
  • In creating a block in Pascal, the following list
    shows the order in which items must be written
  • constants
  • types
  • variables
  • procedures
  • Usually the order in which the procedures are
    defined within a block is unimportant, but
    sometimes the order is crucial to the proper
    execution of the program. This is related to how
    complier works.


40
How the Pascal complier works?
  • The Pascal complier reads a program in the order
    in which it was written, translating as the
    reading takes place.
  • As it encounters new identifiers, it places them,
    along with notes on the properties associated
    with them, in a table (called the symbol table)
  • If any part of the program uses an identifier,
    the complier then refers to the symbol table to
    check that the identifier is being used
    correctly.
  • If the identifier has not been placed in the
    symbol table before it is used, then the complier
    will consider this an error and it will write
    some nasty message to display its unhappiness
    with the programmers behavior. ?

Q if a procedure P1 is to be called by a second
procedure, P2, where should we place the
definition of P1?
Ans Place it before the definition of P2,
because the complier must know about the
characteristics of P1 before P1 can be used by
P2.
41
Problem If procedure P1 calls P2 P2 calls
P1, how should we define these two procedures?
Procedure P2 (A integer B real) forward
  • Procedure P1 (var C real)
  • begin
  • .
  • P2 (X,Y)
  • .
  • end
  • Procedure P2
  • begin
  • .
  • P1(Z)
  • .
  • end
  • This example shows the use of Forward Reference.
  • The directive forward gives the complier all the
    information it needs to know about the procedure
    in order to make an entry in the symbol table.

(Ainteger Breal) forward
42
Procedures Functions
  • Procedures - Section 6
  • Avoiding Errors Debugging

43
Avoiding Errors
  • One of the purposes of procedures is to make
    programs clearer. To achieve this, any procedure
    definition should be written in a way that will
    make its purpose obvious.
  • Choose an identifier for the procedure that shows
    what it does.
  • Choose identifiers for any parameters that shows
    what they represent.
  • Add comments Start each procedure definition
    with a comment explaining the purpose of the
    procedure and the purpose of each parameter.
  • Only use variable parameters when you need
    two-way communication.
  • Avoid using global variables in the procedure all
    the time. Use parameters to communicate between
    procedures and their programs. If global
    variables must be used, that fact should be
    stated clearly in the comment that opens the
    procedure.

44
Debugging
  • Use a snapshot procedure in a program to trace
    changes to variables.
  • Use a driver to test your procedures.
  • Be alert to the mistakes caused by misusing value
    and variable parameters.

Q If you expected a procedure to alter the value
of an argument and the argument is unchanged or
even undefined after a return from the procedure,
what might be wrong?
Ans It may be because the corresponding
parameter was incorrectly declared as a value
parameter.
45
A snapshot procedure Is one that prints the
current values of all variables in a program.
  • Program Ex1
  • var
  • A, B integer
  • C array LowBound..HighBound of integer
  • Procedure Snap (Point integer)
  • var
  • Index integer
  • begin
  • writeln
  • writeln (Snapshot at point , Point1)
  • writeln (A , A1)
  • writeln (B , B1)
  • for Index LowBound to HighBound do
  • write (C, Index1, , CIndex1, )
  • writeln
  • end
  • Begin
  • .
  • Snap (1)

To use it in debugging . Insert calls to the
procedure, each having a different argument, at
various points in the program. . Make the output
from the snapshot procedure self-documenting.
46
  • Program DriverProcessSale
  • var
  • SalesTax, Total real
  • Procedure ProcessSale (BasePrice, TaxRate
    real var Tax, FinalPrice real)
  • Begin
  • Tax BasePrice TaxRate
  • FinalPrice BasePrice Tax
  • end
  • Begin
  • ProcessSale (20.00, 0.07, SalesTax, Total)
  • writeln ( Sales Tax , SalesTax102)
  • writeln (Total Price , Total102)
  • End.

A driver is a dummy main program. It simply
provides the subprogram with appropriate values
for its Input parameters and then, possibly,
prints the values of the output parameters
produced by the subprogram.
47
Procedures Functions
  • Functions - Section 1
  • Introduction

48
Functions Vs. Procedures
  • Both functions and procedures are subprograms.
  • Functions are like procedures.
  • The primary difference is that procedures perform
    some action while functions produce a single
    value.

49
Procedures vs. Functions
  • Writeln (hi, there)
  • This statement uses the predefined procedure
    writeln to perform the action of writing a
    message.
  • The call to writeln is a statement.
  • X 2 sqrt (Y) 5
  • This statement uses the predefined function sqrt
    to obtain the square root of Y.
  • The call to sqrt is a factor in an expression,
    not a complete statement.

50
The function Smaller finds and returns the
smaller of two integers.
  • Function Smaller (First, Second integer)
    integer
  • begin
  • if First lt Second
  • then
  • Smaller First
  • else
  • Smaller Second
  • end

. A function always returns a single value. .
The return values type (called the type of the
function) may be any previously defined simple
data type. But it cannot be a structured type
such as an array or a string. . Within the block
that follows the function heading, there must be
at least one statement that assigns a value of
the appropriate type to the functions
identifier.
51
  • Function Smaller (First, Second integer)
    integer
  • begin
  • if First lt Second
  • then
  • Smaller First
  • else
  • Smaller Second
  • end

All variables shown are of type integer. .
LittleOne Smaller (A, B) . BigOne C D
Smaller (C, D) . LittleRoot sqrt (Smaller
(abs(X), abs(Y))) . Writeln (The smaller value
is , Smaller(EF, 3G)1)
All the calls shown here are valid
52
Procedures Functions
  • Functions - Section 2
  • More Complex Functions

53
The function returns the sum of the elements of
the array RealArray.
  • Program Ex1
  • type
  • RealArrayType array 1..Max of real
  • .
  • Function ArraySum (RealArray RealArrayType)
  • real
  • var
  • Sum real running sum
  • I 1..Max an array index
  • begin
  • Sum 0.0
  • for I 1 to Max do
  • Sum Sum RealArray I
  • ArraySum Sum
  • end
  • Begin
  • .
  • End.

. This example shows the use of local variables
in a function definition so that we can avoid to
use a function identifier on the right side of
assignment statements. Because such use
constitutes a call to the function from within
the definition of the function.
ArraySum 0.0 For I 1 to Max do ArraySum
ArraySum RealArray 1
54
This function computes powers of real values
with integral exponents. If asked to find 00,
it gives an error message and return the value
0e0.
  • Function Power (Base real Exponent integer)
    real
  • var
  • I integer an index variable
  • Result real for interim results
  • begin
  • if Base 0
  • then check exponent
  • if Exponent 0
  • then result is undefined
  • begin
  • writeln (Bad arguments to function power)
  • writeln (Zero returned)
  • Result 0e0
  • end
  • else zero base and non-zero exponent
  • Result 0e0
  • else base ltgt 0 compute Base Exponent
  • .
  • Power Result

. If a subprogram is given bad argument values,
it should try to cope with them and inform the
user both the error and of any corrective action
that may have been taken.
55
This example shows how to use a global variable
to count the number of times that the function
Fun is called.
  • Program Sample (
  • .
  • var
  • FunCount integer
  • .
  • Function Fun (..
  • .
  • Begin
  • .
  • FunCount FunCount 1
  • writeln (Fun has been called , FunCount1,
  • times.)
  • .
  • End
  • Begin
  • FunCount 0
  • .
  • End.

. Functions rarely use global variables they
almost always take their input values only from
their parameters. . Occasionally, global
variables can be useful.
56
Procedures Functions
  • Functions - Section 3
  • Boolean Functions

57
  • Program Example
  • var Age integer
  • Function Teen (Number integer) boolean
  • Teen is a boolean function that returns true
  • if and only if its parameter, Number, is one
    of
  • the number 13, 14, , 19.
  • begin
  • if (Number gt 12) and (Number lt 20)
  • then
  • Teen true
  • else
  • Teen false
  • end
  • begin
  • .
  • If (12 lt Age) and (Age lt 20) then
  • .

This example illustrates how to use boolean
function to improve the clarity of programs.
if Teen (Age) then .
58
Procedures Functions
  • Functions - Section 4
  • Side-Effects

59
This function illustrates an undesirable
side-effect caused by using a global variable.
  • Function FirstBlank (Sentence String) integer
  • var
  • Done boolean a flag true if
    finished
  • begin
  • FirstBlank 0
  • I 0
  • Done false
  • repeat
  • I I 1
  • if I gt StringLength
  • then search for a blank was unsuccessful
  • Done true
  • else
  • if Sentence I
  • then blank found at position I
  • begin
  • FirstBlank I
  • Done true
  • end

. If during its execution, a subprogram changes
the value of a global variable, this is known as
a side-effect of the subprogram.
60
This function illustrates an undesirable
side-effect caused by the alteration of
parameters.
  • Program Example
  • var
  • X, Y real
  • Function FourthRoot (var Number real) real
  • This function returns the value of the fourth
    root of Number by finding the square root of
    the square root of number.
  • begin
  • Number sqrt (Number)
  • FourthRoot sqrt (Number)
  • end
  • begin
  • X 16
  • Y FourthRoot (X)
  • writeln (The fourth root of , X51), is,
    Y51)
  • end.

The output The fourth root of 4.0 is 2.0
. The problem here is that FourthRoot changes the
value of its variable parameter Number. This
change is reflected in a change to the argument.
. As a general rule, value parameters should
always be used in writing function definitions.
61
Procedures Functions
  • Functions - Section 5
  • Avoiding Errors and Debugging

62
Avoiding Errors
  • In writing a function definition, be sure that
    the function identifier is always assigned a
    value.
  • Be careful not to use the function identifier any
    place other than the left side of an assignment
    statement.
  • Avoid to use global variables. Use parameters
    instead.

Function Total (List IntegerArray) integer
Type IntegerArray array 1..Max of integer
Var I integer Begin Total 0 for I
1 to Max do Total Total List I End
Too few arguments in call to Total
63
Debugging
  • Often the program with a function is not what the
    function is doing but rather what values it has
    to work with. If a function does not appear to be
    doing what it was designed to do, check first to
    see if the values of any arguments that are being
    passed to the function are correct.
  • - So, trace the values of all parameters,
    especially on entry to the function.

Example Add the following fragment at the
beginning of the definition of the function
Total. Writeln (Value of List on entry to
Total ) For I 1 to Max do writeln
(List, I1, , ListI
64
  • Program ErrorEx1
  • var
  • A, B integer
  • C array 1..5 of integer
  • Procedure P (A integer, var B real)
  • begin
  • B 1
  • for I1 to 3 do
  • B B A
  • end
  • Procedure R (A integer, B array 1..5 of
    integer )
  • begin
  • Q
  • end
  • Begin
  • .
  • P (1)
  • P (A, 1)
  • A P (1.0, 2)

Possible errors 1. Local variable expected.
In for statement, the index control variable must
be local to the subprogram. 2. Invalid type
specification. 3. Undefined identifier. 4.
Incorrect number of arguments 5. Variable
identifier expected 6. Argument of incorrect
type 7. Invalid from of a call to a procedure.
65
  • Program ErrorEx2
  • var
  • A, B integer
  • type
  • C array 1..5 of integer
  • Procedure Q (A real) forward
  • Function G (A integer, var B C)
  • begin
  • end
  • Function R (A integer) C
  • begin
  • Q (A)
  • S
  • end
  • Procedure Q (A real) forward
  • begin
  • end
  • Begin
  • Q (A)

Possible errors 1. Wrong order of
definition. 2. The type of the function
expected 3. Invalid type of the function. 4.
Assignment to the function identifier
expected. 5. Undefined identifier. 6. Invalid
from of a call to a function.
Write a Comment
User Comments (0)
About PowerShow.com