Download presentation
Presentation is loading. Please wait.
1
Higher Computing Science
Procedures, Functions and Parameters Welcome to the 1st Higher Computing homework webinar. We’re going to look at Procedures and Functions, and how they are used with parameters Procedures and functions are really just ways of making your code more efficient and more easily understood. If you use them your code will be more readable and of course more maintainable.
2
Decomposition When you break your initial programming problem down into smaller more easily solvable sub problems, you will want to code these sub problems as separate sub procedures or functions. Sub-procedures and functions can be tested individually before a program is complete. This makes code easier to debug. As well as making problems more manageable, these sub procedures and functions can be re-used, making your job of writing code easier.
3
Local Variables A Local variable only has scope within the sub- program where it has been defined. PROCEDURE looper() FOR counter FROM 1 TO 10 # Local variable SEND counter TO DISPLAY END FOR END PROCEDURE Lets start with a little revision on variables Some programming languages require you to define variables explicitly with a name and a data type before they are used even if this is not the case it is often a good idea to declare your variables making it easier to keep track of them.
4
Why use local variables?
Local variables mean that they only have a value inside the sub-program they are declared in. Using local variables means that sub-programs are “self contained” and can be reused without affecting the value of variables elsewhere in the program The first point is important as it makes it much more difficult to make a mistake by changing the value of a variable accidentally Ideally re-use means not just re-used within the program they have been written for, but re-used again in other programs – they become part of your own bank of pre-written modules, saving development time as a result. Self contained sub-programs make code easy to test and debug.
5
Why use local variables?
You can use the same variable name again in a different sub-program The memory used by a local variable is freed up when its sub-program has finished running Some additional advantages of using local variables
6
Global Variables Global variables are variables which have scope throughout a program. Any change to the value of a global variable within a sub-program will change its value anywhere else it occurs in the code. Obviously we want to change the values of variables inside a sub program so how do we avoid using global variables? We can control which sub programs are allowed to change the value of a variable by passing them as parameters to that sub program. This is what we are going to look at in this lesson
7
Global Variables Global variables should be avoided as they make your procedures and functions less portable and your code less maintainable The memory required by a global variable is locked up for the entire time your program is running Using Global variables can cause unexpected changes if variables with the same name are used elsewhere in the program
8
A simple procedure This procedure can only perform one task
PROCEDURE eightStars() FOR counter FROM 1 TO 8 # Local variable SEND " * " TO DISPLAY END FOR END PROCEDURE A very simple procedure which prints 8 stars. Not much use if you want to print any other number of stars,
9
Parameters A parameter is a variable which is used to modify how a sub program behaves A parameter is declared in the definition of a sub program (called a formal parameter) Parameters make sub programs more flexible and more portable We are going to look at how a subprogram can use a variable passed to it from outside (called a parameter) Sometimes the sub program will only use the value of that variable, sometimes that sub program will be able to change its value. We are going to look at these two types of parameter.
10
A procedure with a value parameter
This procedure is more flexible as it can be called with any value PROCEDURE stars (INTEGER numberOfStars) FOR counter FROM 1 TO numberOfStars DO SEND " * " TO DISPLAY END FOR END PROCEDURE Number_of Stars is a formal parameter – ie it is being declared in the procedure definition. Some languages require a type definition as well. In this case it is an integer
11
Calling the stars procedure with an actual parameter
PROCEDURE stars (INTEGER numberOfStars) FOR counter FROM 1 TO numberOfStars DO SEND " * " TO DISPLAY END FOR END PROCEDURE DECLARE totalStars AS INTEGER INITIALLY 0 SEND " How many stars?" TO DISPLAY RECEIVE totalStars FROM KEYBOARD stars (totalStars) If the input to the question “How many stars” was 10 then the result would be: * * * * * * * * * * We could call the stars procedure with any value we like.
12
Formal and Actual Parameters
Formal Parameters are variables which are declared when a sub-procedure or function is defined Actual parameters are used when a sub-procedure or function is called A quick re-cap on parameters Formal and actual
13
Formal and Actual parameters
Formal parameter PROCEDURE stars (INTEGER numberOfStars) FOR counter FROM 1 TO numberOfStars DO SEND " * " TO DISPLAY END FOR END PROCEDURE DECLARE totalStars AS INTEGER INITIALLY 0 SEND " How many stars?" TO DISPLAY RECEIVE totalStars FROM KEYBOARD stars (totalStars) Formal parameters are variables which are part of the definition of the sub procedure Actual parameters are variables or values used when the sub procedure is being used (called) Actual parameter
14
Functions
15
How a function differs from a procedure
A function returns a value A procedure performs a sequence of actions Function names are usually nouns Functions return a value so need to be declared as returning a particular data type Procedure names are usually verbs
16
Built in mathematical functions
int() sqr() abs()
17
Using mathematical functions
SET value TO -56 SET newValue TO abs(value) SEND newValue TO DISPLAY Result would be 56
18
Using mathematical functions
SET value TO 4 SET newValue TO sqr(value) SEND newValue TO DISPLAY Result would be 2
19
Using mathematical functions
SET value TO 3.4 SET newValue TO int(value) SEND newValue TO DISPLAY Result would be 3
20
String functions Left$() Right$() Len() Mid$()
Some languages have built in string functions like these
21
Using String Functions
SET myString TO "banana" SET newString TO left$(myString, 2) SEND newString TO DISPLAY newString would have the value "ba"
22
Using String Functions
SET myString TO "banana" SET newString TO right$(myString,2) SEND newString TO DISPLAY newString would have the value "na"
23
Using String Functions
SET myString TO "banana" SET newString TO mid$(myString, 2, 3) SEND newString TO DISPLAY newString would have the value "nan"
24
The validInteger function
FUNCTION validInteger()RETURNS INTEGER DECLARE userInput AS INTEGER INITIALLY 0 RECEIVE userInput FROM KEYBOARD WHILE userInput < 1 OR userInput > 100 DO SEND "Input must be between 1 and 100" TO DISPLAY END WHILE RETURN userInput END FUNCTION As well as built in functions, you can create your own user-defined functions. This one will only accept values between qand including 1 and 100
25
validInteger function
We would call this function within a program: DECLARE number AS INTEGER INITIALLY 0 SET number TO validInteger To give the variable number a value between 1 and 100 This could have been written as a procedure with a parameter but using a function makes the code more readable when it is used in a program
26
The validInteger function with value parameters
FUNCTION validInteger(lowerLimit, upperLimit)RETURNS INTEGER DECLARE userInput AS INTEGER INITIALLY 0 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 KEYBOARD END WHILE RETURN userInput END FUNCTION
27
Calling the validInteger 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: SEND "What is the maximum input value" TO SCREEN RECEIVE maxInput FROM (INTEGER) KEYBOARD SET numberToUse TO validInteger(1,maxInput) This function call would return a value between 1 and maxInput. So if we wanted several different inputs from the user with different upper and lower limits, we can use the same input validation function each time, but with different parameters.
28
Why user defined functions?
Functions return a value Functions make code more readable Functions, like procedures can be reused so make programming more efficient
29
Parameters passed by Value
A parameter passed by value is one which is passed into a procedure or function and whose value is used by that procedure When a sub procedure is called with a variable passed by value, 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 A quick re-cap on parameters.
30
Parameters passed by Reference
When a sub procedure is declared with a formal parameter passed by reference then when it is called with an actual parameter its value is changed by that sub procedure. When a variable is passed by reference the reference is to the memory location of the variable itself. No copy is being made. NB Not all programming languages make the distinction between value and reference parameters. Some languages need you to declare a parameter as a reference parameter otherwise it assumes that you are intending to use it as a value parameter
31
Parameters passed by Reference
The value of the variable changes as a result of calling the sub procedure with it as a parameter PROCEDURE swap (a, b) DECLARE temp AS INTEGER INITIALLY 0 SET temp TO a SET a TO b SET b TO temp END PROCEDURE Note that temp is a local variable. It only has a value inside the swap procedure
32
Parameters passed by Reference
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
33
Parameters passed by Reference
PROCEDURE get_values() RECEIVE a (INTEGER) FROM KEYBOARD RECEIVE b (INTEGER) FROM KEYBOARD END PROCEDURE PROCEDURE DisplayAndSwapValues() SEND "The value of a is " & a TO DISPLAY SEND "The value of b is " & b TO DISPLAY swap (a, b) PROCEDURE swap (a, b) DECLARE temp AS INTEGER INITIALLY 0 SET temp TO a SET a TO b SET b TO temp
34
Parameters passed by Reference
Example: Write a program allows the user to swap the positions of any two values in an array
35
The printArray procedure
PROCEDURE printArray (numbers) FOR counter = 0 TO 5 DO SEND numbers[counter] TO DISPLAY END FOR END PROCEDURE
36
The swap procedure PROCEDURE swap (a, b)
DECLARE temp AS INTEGER INITIALLY 0 SET temp TO a SET a TO b SET b TO temp END PROCEDURE Note that temp is a local variable. It only has a value inside the swap procedure
37
Parameters passed by Reference
DECLARE numbers AS ARRAY OF INTEGER INITIALLY [1,3,5,7,9 11] PROCEDURE mainProgram (numbers) printArray (numbers) SEND "Please enter index position 1 to swap" TO DISPLAY RECEIVE index1 (INTEGER) FROM KEYBOARD SEND "Please enter index position 2 to swap" TO DISPLAY RECEIVE index2 (INTEGER) FROM KEYBOARD swap (numbers[index1], numbers[index2] ) END PROCEDURE Index1 and index2 are local variables inside the program The numbers array is a reference parameter in the mainProgram procedure definition The numbers array is passed to the printArray sub program
38
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.
39
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 The advantages of using parameter passing rather than global variables is to increase the modularity, portability readability and maintainability of the code. A formal parameter is one declared in the definition of a procedure or function An actual parameter is one used when calling a procedure or function 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
40
Summary 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. Using procedures and functions improves the readability and maintainability of code Procedures and functions which use local variables make code more portable Procedures and functions can be tested independently making code easier to debug
41
Question Examples 2016 Q10b, c, d 2015 Q14c Specimen Paper Q9c Example Paper Q9b(ii) Example Paper Q11a, b Old Higher 2012 Q22 Old Higher 2011 Q10c
42
2016 Q10b (b) Mrs McColl implements the program using global variables. Another teacher suggests that she makes use of parameter passing instead. State two benefits of using parameter passing rather than global variables.
43
2016 Q10b 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
44
2016 Q10c (c) Parameters are used to pass data between subprograms. Parameters can be passed by reference or passed by value. Explain why passing by value is more demanding on system resources when the data being passed is held in an array.
45
2016 Q10c Passing a parameter by value means that a copy of that parameter is made while the procedure is running. This means that more memory resources are being used and more processor instructions are needed to manage it.
46
2016 Q10d d) Mrs McColl’s program is modular and makes use of functions. Explain what is meant by a function.
47
2016 Q10d A function returns a single value The value of a function can be assigned to a variable eg. Uservalue = validInteger (1, 10)
48
2015 Q 14c An algorithm is implemented to validate the applicant’s data from the application form shown. There are two subprograms at lines two and three. The parameters for these subprograms are not shown. Name a parameter that should be passed at line 2, state the type of parameter passing used and justify your answer. Line 1 REPEAT Line 2 Enter_applicant_data(…) Line 3 Validate_form_data(…) Line 4 UNTIL <form data is valid>
49
2015 Q 14c The parameter could be any item from the form such as title, first name, surname etc. It will be passed by reference because the value will be updated and then passed back out of the sub-program PROCEDURE validate_form_data(gender) RECEIVE gender FROM (CHARACTER) KEYBOARD WHILE gender ≠ "M" AND gender ≠ "F" < error message> END WHILE END PROCEDURE
50
Specimen Paper Q 9c Jeanette works for a bank and has downloaded a taxCode function, from their online library. Bank employees receive an annual salary and bonus pay and Jeanette’s program stores these values in variables salary and bonus. It also stores the employee’s tax code in a variable called code. Using pseudocode or a language with which you are familiar, write an algorithm for a subroutine that will: Ask the user for the values for variables salary and bonus Use the function to assign the variable code Display code on screen
51
Specimen Paper Q 9c PROCEDURE calculateCode RECEIVE salary FROM KEYBOARD RECEIVE bonus FROM KEYBOARD SET code TO taxCode (salary, bonus) SEND code TO DISPLAY END PROCEDURE
52
Example Paper Q9b(ii) When implementing code, a programmer can limit the scope of a variable. Explain what is meant by scope and how it can be limited. Scope is the section of code in which a variable can be used and has a value You can create a local variable by declaring it inside sub-program or by defining a formal parameter which is used inside that sub-program.
53
Example Paper Q11a A function used to perform an arithmetical operation is shown below: FUNCTION combinations (INTEGER number) RETURNS INTEGER SET factor TO 1 FOR counter FROM 1 TO number DO SET factor TO counter * factor END FOR RETURN factor END FUNCTION State the formal parameter in the function. The formal parameter is number
54
Example Paper Q11b A program has two variables called items and permutations which contain the values 3 and 0 respectively, as shown below: Explain what is meant by an actual parameter, by referring to the following line of code used to call the function above: SET permutations TO combinations(items) State the values contained in items and permutations after execution of the line of code. Explain your answer The actual parameter is the one used when calling the combinations procedure
55
Example Paper Q11b SET permutations TO combinations(items)
FUNCTION combinations (INTEGER number) RETURNS INTEGER SET factor TO 1 FOR counter FROM 1 TO number DO SET factor TO counter * factor END FOR RETURN factor END FUNCTION SET permutations TO combinations(items) State the values contained in items and permutations after execution of the line of code. Explain your answer We call the function with the actual parameter items (value is 3) Factor is set initially to 1 From counter 1 to 3 we set factor to counter * 3 Factor = 1 X 1 =1 2 X 1 =2 then 3 X 2 = 6
56
Example Paper Q11b items = 3 permutations = 6
items is unchanged by the function (it is still 3) We call the function with the actual parameter items (value 3) The loop executes three times factor is set initially to 1 For counter from 1 to 3 we set factor to counter * 3 factor = 1 X 1 =1 then 2 X 1 =2 then 3 X 2 = 6
57
Old Higher 2012 Q22 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 < 500 THEN SET band TO "cheap" END IF IF cost_per_person >= 500 AND cost_per_person < 2000 THEN SET band TO "medium" IF cost_per_person >= 2000 THEN SET band TO "expensive"
58
Old Higher 2012 Q22 (c) 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. (d) Explain the term concatenation. (e) Explain the term function.
59
Old Higher 2012 Q22 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
60
Old Higher 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. (a) State the most suitable data type for the parameter called cost. Parameter Description amount Number of tickets category adult, child, student, OAP cost Total cost of required tickets
61
Old Higher 2009 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. The most suitable data type for the parameter cost is REAL since it will be storing a decimal value Parameter Description amount Number of tickets category adult, child, student, OAP cost Total cost of required tickets
62
Old Higher 2009 Parameter Description amount Number of tickets category adult, child, student, OAP cost Total cost of required tickets 1. Get ticket details 2. Calculate cost 3. Display cost and accept payment 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.
63
Old Higher 2009 1. Get ticket details 2. Calculate cost 3. Display cost and accept payment Amount or Category can be passed by value into calculateCost since they are not being changed Cost will be passed by reference since it is being passed out of calculateCost and into the Display cost and accept payment procedure
64
Old Higher 2009 The program will make use of a 1-D array.
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.
65
Old Higher 2009 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.
66
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?
67
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 be 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)
68
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 The advantages of using parameter passing rather than global variables is to increase the modularity, portability readability and maintainability of the code. A formal parameter is one declared in the definition of a procedure or function An actual parameter is one used when calling a procedure or function 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
69
Summary 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. Using procedures and functions improves the readability and maintainability of code Procedures and functions which use local variables make code more portable Procedures and functions can be tested independently making code easier to debug
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.