Proceduresx_Functions_and_Parameters

advertisement
Software Development
Sub Procedures, Functions and
Parameters
Local Variables
A Local variable only has scope within the subprocedure where it has been defined.
PROCEDURE Looper()
FOR counter FROM 1 TO 10
SEND counter TO DISPLAY
END FOR
END PROCEDURE
Why use local variables?
• Local variables mean that they only have a
value inside sub-procedure they are
declared in.
• Using local variables means that subprocedures are “self contained” and can
be reused without affecting the value of
variables elsewhere in the program
Why use local variables?
• You can use the same variable name
again in a different sub-procedure
• The memory used by a local variable is
freed up when its sub-procedure has
finished running
Global Variables
• Global variables are variables which have
scope throughout a program.
• Any change to the value of a global
variable within a sub-procedure will
change its value anywhere else it occurs
in the program.
Global Variables
• Global variables are best avoided as they
make your procedures and functions less
portable and your code less maintainable
A procedure without Parameters
This Sub-Procedure can only perform one task
PROCEDURE Eight_stars()
FOR counter FROM 1 TO 8 # Local variable
SEND " * " TO DISPLAY
END FOR
END PROCEDURE
A sub procedure with a value
Parameter
This sub-procedure is more flexible as it can be called
with any value
PROCEDURE Stars (number_of _stars)
FOR counter FROM 1 TO number_of_stars
SEND " * " TO DISPLAY
END FOR
END PROCEDURE
Calling the sub procedure
SEND " How many stars?" TO DISPLAY
RECEIVE number_of _stars (INTEGER) FROM KEYBOARD
Stars (number_of _stars)
PROCEDURE Stars (number_of _stars)
FOR counter FROM 1 TO number_of_stars
SEND " * " TO DISPLAY
END FOR
END PROCEDURE
If the input to the question “How many stars” was 10
then the result would be:
**********
Parameters
• Formal Parameters are variables which
are declared when a sub-procedure or
function is defined
• Actual parameters are used when a subprocedure or function is called
Functions
How a function differs from a
procedure
• A function returns a value
• A procedure performs a sequence of actions
• Function names and usually nouns
• Functions return a value so need to be declared
as being a particular data type
• Procedure names are usually verbs
Built in mathematical functions
• int()
• sqr()
• abs()
Using mathematical functions
SET value TO -56
SET newValue TO abs(value)
SEND newValue TO DISPLAY
Result would be 56
Using mathematical functions
SET value TO 4
SET newValue TO sqr(value)
SEND newValue TO DISPLAY
Result would be 2
Using mathematical functions
SET value TO 3.4
SET newValue TO int(value)
SEND newValue TO DISPLAY
Result would be 3
Built in string functions
•
•
•
•
Left$()
Right$()
Len()
Mid$()
Using String Functions
SET myString TO "banana"
SET newString TO left$(myString, 2)
SEND newString TO DISPLAY
Result would be ba
Using String Functions
SET myString TO "banana"
SET newString TO right$(string, 2)
SEND newString TO DISPLAY
Result would be na
Using String Functions
SET myString TO "banana"
SET newString TO mid$(string, 2, 3)
SEND newString TO DISPLAY
Result would be nan
Validnumber function
FUNCTION ValidInteger()RETURNS INTEGER
RECEIVE userInput FROM (INTEGER) KEYBOARD
WHILE userInput < 1 OR userInput > 100 DO
SEND "Input must be between 1 and 10 TO DISPLAY
RECEIVE userInput FROM (INTEGER) KEYBOARD
END WHILE
RETURN userInput
END FUNCTION
Validnumber function
We would call this function within a program:
SET number TO ValidInteger
To give the variable number a value
between 1 and 100
Validnumber function with value
parameters
FUNCTION ValidInteger(lowerLimit, upperLimit)RETURNS INTEGER
RECEIVE userInput FROM (INTEGER) KEYBOARD
WHILE userInput < lowerLimit OR userInput > upperLimit DO
SEND "Input must be between "& lowerLimit " and "
&upperLimit" TO DISPLAY
RECEIVE userInput FROM (INTEGER) KEYBOARD
END WHILE
RETURN userInput
END FUNCTION
Input Validation (Function)
We could call this function with actual parameters, 1 and 50 to return a
number between 1 and 50:
SET numberToUse TO ValidInteger(1,50)
or we could call it with the actual parameters 1 and inputRange which is a
variable which has a value assigned elsewhere in the program:
RECEIVE
inputRange FROM (INTEGER) KEYBOARD
SET numberToUse TO ValidInteger(1,inputRange)
This call would return a value between 1 and inputRange.
Why user defined functions?
• Functions return a value
• Functions make code more readable
• Functions, like procedures can be reused
so make programming more efficient
Value Parameters
• A value parameter is one which is passed into a sub
procedure or function and whose value is used by that
procedure
• When a sub procedure is called with a variable as a
value parameter, a copy of that variable is made using its
formal parameter while the procedure is running.
• The copy of the variable is destroyed when the
procedure has completed, so the memory can be reused
Reference Parameters
• When a sub procedure is declared with a
reference parameter then when it is called
with an actual variable its value is
changed by that sub procedure.
• When a variable is passed as a reference
parameter, the reference is to the memory
location of the variable itself. No copy is
being made.
Reference Parameters
The value of the variable changes as a result of
calling the sub procedure with it as a parameter
PROCEDURE swap (REF a, REF b)
SET temp TO a
SET a TO b
SET b TO temp
END PROCEDURE
Reference Parameters
Write a program which asks for two values
(stored in the variables a and b) prints their
values, then swaps the contents of the variables
around and prints the new values
Reference Parameters
PROCEDURE Get_values()
RECEIVE a (INTEGER) FROM KEYBOARD
RECEIVE b (INTEGER) FROM KEYBOARD
End Sub
PROCEDURE SwapValues()
SEND "The value of
SEND "The value of
swap (a, b)
SEND "The value of
SEND "The value of
End Sub
a is " & a TO DISPLAY
b is " & b TO DISPLAY
a is " & a TO DISPLAY
b is " & b TO DISPLAY
PROCEDURE swap (REF a, REF b)
SET temp TO a
SET a TO b
SET b TO temp
END PROCEDURE
Reference Parameters
Example: Write a program allows the user to swap
the positions of any two values in an array
Reference Parameters
PROCEDURE swap (REF a, REF b)
SET temp TO a
SET a TO b
SET b TO temp
END PROCEDURE
Reference Parameters
PROCEDURE main_program_click (REF numbers)
Print_array
numbers [ ]
SEND "Please enter index position 1 to swap" TO DISPLAY
RECEIVE index1 FROM KEYBOARD
SEND "Please enter index position 2 to swap" TO DISPLAY
RECEIVE index2 FROM KEYBOARD
swap (numbers [index1], numbers [index2] )
Print_array
numbers[ ]
END PROCEDURE
Parameter Passing
Parameter passing by value creates a copy of
the variable when the sub procedure is called
- this is inefficient if the variable is an array.
Arrays are normally passed as reference
parameters because of the memory space
they occupy.
Question Examples
SQA 2012
A travel agent uses a suite of software to help advertise holidays and make
bookings. Part of the pseudocode that was written for the software is:
if cost_per_person is less than 500
set band to ‘cheap’
end if
if cost_per_person is greater than or equal to 500 AND cost_per_person is less
than 2000
set band to ‘medium’
end if
if cost_per_person is greater than or equal to 2000
set band to ‘expensive’
end if
SQA 2012
When the above is implemented as a subroutine, state
whether the variable “cost_per_person” would be passed
by reference or value. Justify your answer.
Each holiday booking is assigned a unique reference code.
The software which creates this code uses concatenation
within a user-defined function.
•Explain the term concatenation.
•Explain the term function.
SQA 2012
•The variable cost_per_person” would be
passed by value because it is not going to
be changed by the program
•The term concatenation means to join two
or more strings together to make one string
•A function is a section of code which returns
a single value
SQA 2010
A teacher tells their pupils that they must avoid the
use of global variables in their programs where
possible.
•State the meaning of the term “global variable”.
•Explain why the pupils have been asked to avoid
the unnecessary use of global variables when
programming.
SQA 2010
• A global variable is a variable which can be accessed throughout a program.
•Using Global variables can cause unexpected changes if variables with the
same name are used in the program
•The code is less readable because it is not obvious how data is flowing
between procedures
•Memory used by local variables is reused once the procedure has completed
its task but global variables will always be using memory resources
•Procedures declared with parameters can be re-used making the code more
modular and the code more portable
SQA 2011
(c) Explain one difference between a
procedure and a function
A well written program should make use of
parameter passing.
(i) State the purpose of an in parameter.
(ii) State the purpose of an out parameter.
SQA 2011
A function can only return a single value whereas
a procedure can return any number of values
The value of a function can be assigned to a
variable eg. Uservalue = validnumber 1, 10
in parameter: a variable passed into a sub
procedure whose value is used but not changed
out parameter: a variable passed into a procedure
whose value is changed by that procedure
SQA 2010
A tower block has 38 floors, each with 25 rooms. A label for a room will consist of the floor number and
the room number. The design for a labelling program is shown below.
For each of 38 floors
For each of 25 rooms
Display “Floor Number:” and floor_no
Display “Room Number:” and room_no
Next room
Display two blank lines
Next floor
In order for Henry’s program to operate correctly for any office building two parameters would have to
be passed to it.
(i) State what these two parameters would be.
State whether these parameters would be passed to the subprogram by value or by reference. Justify
your answer.
SQA 2010
• Number of floors in the building (floor_no)
• Number of rooms on each floor (room_no)
• These variables would be passed by value
since the values are only used, not
changed
SQA 2009
A program is created during the implementation
stage of the software development process.
(a) Programmers may make use of a module
library. State what is meant by the term “module
library”.
(b) The program may require a user-defined
function. State what is meant by the term “userdefined function”.
SQA 2009
A module library is a collection of pre-written/pre-tested
sections of code which can be re-used
A user defined function is one which created by the
programmer, not already built in. which returns a single
value
SQA 2009
A cinema ticket system allows customers to select and pay for their own
tickets.
The top level algorithm is:
1. Get ticket details
2. Calculate cost
3. Display cost and accept payment
The module CalculateCost uses the number of tickets and the category of
ticket to calculate the total payment due. It uses the parameters described below.
Parameter
Description
Amount
Number of tickets
Category
adult, child, student, OAP
Cost
Total cost of required tickets
(a) State the most suitable data type for the parameter called Cost.
SQA 2009
The module CalculateCost uses the number of tickets and
the category ofticket to calculate the total payment due. It
uses the parameters described below.
Parameter
Description
Amount
Number of tickets
Category
adult, child, student, OAP
Cost
Total cost of required tickets
The most suitable data type for the parameter Cost is real
or currency since it will be storing a decimal value
SQA 2009
1. Get ticket details
2. Calculate cost
3. Display cost and accept payment
Parameter
Description
Amount
Number of tickets
Category
adult, child, student, OAP
Cost
Total cost of required tickets
Parameters can either be passed by value or by
reference.
(i) Identify one parameter that is passed by value to
the module CalculateCost. Justify your answer.
(ii) Identify one parameter that is passed by reference
to the module CalculateCost. Justify your answer.
SQA 2009
1. Get ticket details
2. Calculate cost
3. Display cost and accept payment
Parameter
Description
Amount
Number of tickets
Category
adult, child, student, OAP
Cost
Total cost of required tickets
Amount or Category can be passed by value into
Calculate Cost since they are not being changed
Cost will be passed by reference since it is being
passed out of Calculate Cost and into the Display
cost and accept payment procedure
SQA 2009
(c) A program may use local variables and
global variables.
(i) What is the scope of a global variable?
(ii) State two advantages of using parameter
passing rather than global variables when
programming.
SQA 2009
The scope of a global variable is throughout
the program.
The advantages of using parameter passing
rather than global variables is to increase the
modularity, portability readability and
maintainability of the code.
SQA 2009
The program will make use of a 1-D array.
(i) When creating, or declaring, a 1-D array for
use in a program, a name must be given to the
array. State two other items that should be
specified when the array is created.
(ii) Explain why it is a more efficient use of system
resources to pass an array by reference
rather than by value.
SQA 2009
(i) When creating, or declaring, a 1-D array you
need to state the number of items in the array
(its index) and the data type (integer, string
boolean etc)
(ii) Passing an array by reference is more efficient
than passing by value because arrays
consume large amounts of memory and since
when a parameter is passed by value, a copy
is made, memory is consumed unnecessarily.
2008
A holiday booking website includes a currency converter which asks for
the amount in pounds sterling and converts it to euros. Here is the toplevel algorithm, including data flow for steps 1 and 2.
1. get amount of pounds (out: pounds)
2. calculate euros (in: pounds out: euros)
3. display conversion
(a)State which design notation is being used.
(b) Step 3 results in the following being displayed on screen:
£500 converts to 750 euros. State the data flow for step 3.
(c) Identify whether the pounds variable in step 1 should be passed by
value or passed by reference. Explain your answer.
2008
1. get amount of pounds (out: pounds)
2. calculate euros (in: pounds out: euros)
3. display conversion
(a) The design notation being used is pseudocode
(b) The data flow for step 3 is (in: pounds in: euros)
(c) In step 1 pounds should be passed by reference
because it is being given a value which is then passed
out of step 1 and into steps 2 and 3
SQA 2008
• During the development of the software,
module libraries are used. The
• modules limit the scope of certain
variables.
• (i) What is a module library?
• (ii) Describe one way in which the scope of
a variable may be limited.
• (iii) Explain why the programmer might
want to limit the scope of a variable.
Another example
The design for a program is shown below.
1. Initialise variables
2. Enter pupil marks
3. Count the number of pupils with less than 45 marks
4. Display results.
(b) Step 3 of the program uses the parameters PupilMark
and NoNeedingSupport.
(i) State the variable types for these parameters.
(ii) For each parameter, state if it should passed by value or
by reference in step 3?
Another example
The design for a program is shown below.
1. Initialise variables
2. Enter pupil marks
3. Count the number of pupils with less than 45 marks
4. Display results.
(i) and NoNeedingSupport would integer
(ii) In step 3, PupilMark would be passed by value and
NoNeedingSupport would be passed by reference
(because it is passed out and then into step 4)
Summary
•
A Local variable only has scope within the-sub procedure where it has been
defined. A global variable has scope throughout a program. Using global
variables makes code less readable, less modular and thus less
maintainable
•
A value parameter is one which is passed into a sub-procedure and whose
value is copied, used by that procedure then discarded. A reference
parameter is a variable which is passed into a sub-procedure and then out
again and whose value is changed by that sub- procedure
•
The advantages of using parameter passing rather than global variables is
to increase the modularity, portability readability and maintainability of the
code.
•
A function returns a value, a procedure performs a sequence of actions
•
A built in function is supplied as part of the development environment, a
user defined function is one created by the programmer.
Download