0% found this document useful (0 votes)
23 views

T1 Procedures and Functions

Programming Concepts Unit 8 - Procedures and functions

Uploaded by

Nazril Rosly
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

T1 Procedures and Functions

Programming Concepts Unit 8 - Procedures and functions

Uploaded by

Nazril Rosly
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Objectives

• Understand the concept of procedures and functions


• Learn how to write simple procedures and functions
• Understand and use parameters to pass data to procedures
and functions
• Know that procedures and functions may use local variables
which are accessible only within them
• Use local variables and explain why it is good
practice to do so
Procedures and functions
Unit 10 Advanced programming and databases

Starter
OUTPUT "menu"
• A computer program OUTPUT "1: New file"
needs a menu to appear OUTPUT "2: Edit file"
OUTPUT "3: Delete file"
• A programmer writes the OUTPUT "4: Quit"
OUTPUT "5: Show menu"
code shown on the right
• What is wrong with this code? choice ← USERINPUT
IF choice = "5"
• What alternative could
THEN
be used? OUTPUT "1: New file"
OUTPUT "2: Edit file"
OUTPUT "3: Delete file"
OUTPUT "4: Quit"
OUTPUT "5: Show menu"
ENDIF
Procedures and functions
Unit 10 Advanced programming and databases

Starter
OUTPUT "menu" OUTPUT "1: New file"
OUTPUT "1: New file" OUTPUT "2: Edit file"
OUTPUT "2: Edit file" OUTPUT "3: Delete file"
OUTPUT "3: Delete file" OUTPUT "4: Quit"
OUTPUT "4: Quit" OUTPUT "5: Show menu"
OUTPUT "5: Show menu"
choice ← USERINPUT
IF choice = "5"
THEN
ENDIF
• What is wrong with this code? • What alternative could be
used?
• The programmer has copied and Subroutines – in this case a
pasted parts of the code which can procedure
lead to mistakes being introduced if
one part is corrected and not the
other
Procedures and functions
Unit 10 Advanced programming and databases

Using subroutines
• As your programs become larger and more complex,
they need to be broken down into smaller,
self-contained sections
• Here is an illustration of the concept:

Make a lemon
meringue pie

Make the Make the Make the


pastry filling meringue
Procedures and functions
Unit 10 Advanced programming and databases

Functions and procedures


• Subroutines allow code that you intend to use
a number of times to be grouped together under
one name
• Both functions and procedures are subroutines
• Values can be passed to both procedures and functions
• Functions will return a value after processing has taken place
Procedures and functions
Unit 10 Advanced programming and databases

Built-in subroutines
• All programming languages have built-in procedures
and functions to perform common tasks
• You have like already used built-in subroutines such as these
in Python:
print("Hello")
input("Type in your name: ")

random(1,6)
• For each of the above subroutines, explain whether
they are functions or procedures
Procedures and functions
Unit 10 Advanced programming and databases

Built-in functions
print("Hello") # a procedure to output
text
input("Type in your name: ") # a function that
returns
# what the user enters
random(1,6) # a function that
returns an
# integer between 1 and
6

• Procedures execute code in a subroutine – but they


don’t return anything
• Functions will return something, so input returns what the
user typed in, random returns a number
• Both functions and procedures can have parameters
which allow values to be passed to them:
Procedures and functions
Unit 10 Advanced programming and databases

Built-in functions
print("Hello") # a procedure to output
text
input("Type in your name: ") # a function that
returns
# what the user enters
random(1,6) # a function that
returns an
# integer between 1 and
6

• Both functions and procedures can have parameters


which allow values to be passed to them:
• The values "Hello", "Type in your name: ", 1, 6 are
the parameters in the above code
Procedures and functions
Unit 10 Advanced programming and databases

A program using procedures


• A racing game requires the following:
• Display a menu
• Display the keyboard controls for the game
• Display high scores in the game

Racing game

showMenu() showKeys() showHighScores()


Procedures and functions
Unit 10 Advanced programming and databases

showMenu procedure
PROCEDURE showMenu
OUTPUT " Menu "
OUTPUT "=================="
OUTPUT "1: Play game"
OUTPUT "2: Show key controls"
OUTPUT "3: High scores"
OUTPUT "4: Return to main menu"
OUTPUT "5: Exit game"
ENDPROCEDURE
This calls the procedure
CALL showMenu named showMenu

• How many parameters does showMenu have?


• Write a procedure that will show the keyboard controls
of the game
Procedures and functions
Unit 10 Advanced programming and databases

showKeys procedure
PROCEDURE showKeys
OUTPUT "Keyboard controls"
OUTPUT "================="
OUTPUT "1: Up arrow - forwards"
OUTPUT "2: Down arrow – backwards/brake"
OUTPUT "3: Left arrow – turn left"
OUTPUT "4: Right arrow – turn right"
OUTPUT "5: R - refuel“
ENDPROCEDURE
CALL showKeys
• Both showKeys and showMenu have no parameters
Procedures and functions
Unit 10 Advanced programming and databases

Worksheet 1
• Now complete Task 1 on Worksheet 1
Procedures and functions
Unit 10 Advanced programming and databases

Functions
• Functions work just like procedures, except at the
end they will return a value
FUNCTION sum(a, b)
total ← a + b
This is a function as it
RETURN total
returns a value
ENDFUNCTION
answer ← sum(5, 3)
OUTPUT answer

• What is the output from the above function?


• Explain how it works
Procedures and functions
Unit 10 Advanced programming and databases

Functions
FUNCTION sum(a, b) • First sum(5,3) calls the sum function
• The values 5 and 3 are passed to
total ← a + b
the sum function
RETURN total • The sum function adds 5 + 3 and
ENDFUNCTION stores 8 in total
• The sum function returns the result
answer ← sum(5, 3) of 8 to the function call
OUTPUT answer • This is then assigned to the variable
called answer
• answer (which contains 8) is then
• Output: 8 output
• Write a function named ‘greatest’ that has three
parameters which are numbers
• The function needs to return the greatest of the
three numbers
Procedures and functions
Unit 10 Advanced programming and databases

Functions
FUNCTION greatest(a, b, c)
IF a > b AND a > c
THEN
RETURN a
IF b > a AND b > c
THEN
RETURN b
ELSE
RETURN c
ENDFUNCTION
Procedures and functions
Unit 10 Advanced programming and databases

Passing parameters
• When you create a function with the statement:
sum(a, b)
• a and b are known as parameters
• Data types can be given for each parameter:
sum(a : REAL, b : REAL) RETURNS REAL
Try this problem:
An average score is calculated by dividing a total
score by the number of attempts
• Create a function to calculate an average score
Procedures and functions
Unit 10 Advanced programming and databases

Pseudocode for average


FUNCTION averageScore(totalScore : INTEGER, numScores : INTEGER)
RETURNS REAL
avg ← totalScore / numScores
RETURN avg
ENDFUNCTION

• To call the function:


OUTPUT "Enter total score: "
INPUT total
OUTPUT "Enter number of scores: "
INPUT n
OUTPUT averageScore(total, n)
Procedures and functions
Unit 10 Advanced programming and databases

Worksheet 1
• Now complete Task 2 and Task 3 on Worksheet 1
Procedures and functions
Unit 10 Advanced programming and databases

Why use subroutines?


• They are useful to break up a large program into
self-contained units
• Each subroutine can be tested separately to make sure it
works correctly
• Many programmers can work on a large program at the same
time, cutting down development time
• Subroutines can be re-used in other programs

• What is one other advantage of using subroutines?


Procedures and functions
Unit 10 Advanced programming and databases

More advantages of
using subroutines
• Subroutines can be stored in a subroutine library
and used in different programs if required
• Program maintenance is easier – if requirements
change then just the affected subroutines need to be
modified
Procedures and functions
Unit 10 Advanced programming and databases

Local variables and scope


• The ‘scope’ of a variable, constant, procedure or
function defines the parts of the program in which it
is recognised and can be used
• When you use an inbuilt function or procedure, you
can write, for example
x ← sqrt(y)
• In the random function you don’t need to worry
about the internal variables or how they are used
• This is because the variables used are only recognised within
the function itself
Procedures and functions
Unit 10 Advanced programming and databases

Variable scope
• Variables var1 and var2 Variables var1, var2
are global variables and FUNCTION s1()
can be seen anywhere in variables a, b, c
the program ENDFUNCTION

• Variables a, b and c can


only be seen and used FUNCTION s2()
inside s1 variables x, y, z
ENDFUNCTION
• Variables x, y and z can
only be seen and used
inside s2
Procedures and functions
Unit 10 Advanced programming and databases

Variable scope
• Think of each function as being a house with
reflective windows – you can see out, but no one
outside can see the variables in the ‘house’
Procedures and functions
Unit 10 Advanced programming and databases

Variable scope

Subroutine A Subroutine B Subroutine C


• If you are in one of the functions, you cannot see
any variables in the other functions
• If you are in a function “house”, you can see and use
global variables in the main program
Procedures and functions
Unit 10 Advanced programming and databases

Local and global variables


• Local variables only exist while the function or
procedure is executing
• They are only accessible within the particular function
or procedure
• Global variables are accessible anywhere in
the program
Procedures and functions
Unit 10 Advanced programming and databases

What is output by this program?


PROCEDURE changeNum
num ← 6 This is a local variable

OUTPUT num Outputs 6

ENDPROCEDURE
#Main program
This isn’t affected by anything happening in the
num ← 5 changeNum subroutine

OUTPUT num Outputs 5

#call function changenum


CALL changeNum Calls changeNum

OUTPUT num Outputs 5 – the num variable in changeNum is different


Procedures and functions
Unit 10 Advanced programming and databases

Example
• Identify the local variables in function calcmax
FUNCTION calcmax(heights)
max ← heights[1]
n ← LENGTH(heights)
FOR count ← 1 TO n
IF heights[count] > max
THEN
max ← heights[count]
ENDIF
NEXT n
RETURN max
ENDFUNCTION
• What type of data structure is heights?
• How will the function be called?
Procedures and functions
Unit 10 Advanced programming and databases

Answer
• max, n and count are all local variables
FUNCTION CalcMax(heights) // heights is an array
max ← heights[1]
n ← LENGTH(heights)
FOR count ← 1 TO n
IF heights[count] > max
THEN
max ← heights[count]
ENDIF
NEXT count
RETURN max
ENDFUNCTION
• The function is called and the result stored with a
statement such as:
tallest ← CalcMax(pupilHeights)
• The value max will be returned to tallest
Procedures and functions
Unit 10 Advanced programming and databases

Global and local constants


• Constants follow the same rules as variables
• A constant cannot be changed once declared
• priceWithVAT is a local variable. This means it is only accessible
inside the addVAT subroutine
FUNCTION addVAT(netPrice : REAL) RETURNS REAL
vat ← netPrice * VAT_RATE
priceWithVAT ← netPrice + vat
RETURN priceWithVAT
ENDFUNCTION

CONSTANT VAT_RATE ← 0.20


priceNoVAT ← 50.00
sellingPrice ← addVAT(priceNoVAT)
OUTPUT sellingPrice
Procedures and functions
Unit 10 Advanced programming and databases

Advantages of using
local variables
• Local variables keep a subroutine self-contained,
so it can be used in any program without variable
names conflicting with those used in the calling
program
• Generally, you should use local variables wherever you
possibly can
Procedures and functions
Unit 10 Advanced programming and databases

Worksheet 1
• Now complete Task 4 on Worksheet 1
Procedures and functions
Unit 10 Advanced programming and databases

Plenary
• Answer the following questions in pairs
• What are two types of subroutine used in programming?
• How many parameters can functions and procedures have?
• Explain the difference between a local and global variables
• What are three reasons that you should try to use subroutines
where possible?
Procedures and functions
Unit 10 Advanced programming and databases

Plenary
• Two types of subroutine used in programming:
• Functions and procedures

• How many parameters can functions and


procedures have? – Zero, one or many
• Explain the difference between a local and global
variables
• Globals are accessible anywhere in the program – locals
only within the subroutine in which they were created
• What are three reasons that you should try to use
subroutines where possible?
• Reuse code, decomposition, more maintainable code
Procedures and functions
Unit 10 Advanced programming and databases

Copyright

© 2021 PG Online Limited

The contents of this unit are protected by copyright.

This unit and all the worksheets, PowerPoint presentations, teaching guides and other associated files
distributed with it are supplied to you by PG Online Limited under licence and may be used and copied by you
only in accordance with the terms of the licence. Except as expressly permitted by the licence, no part of the
materials distributed with this unit may be used, reproduced, stored in a retrieval system, or transmitted, in any
form or by any means, electronic or otherwise, without the prior written permission of PG Online Limited.

Licence agreement

This is a legal agreement between you, the end user, and PG Online Limited. This unit and all the worksheets,
PowerPoint presentations, teaching guides and other associated files distributed with it is licensed, not sold, to
you by PG Online Limited for use under the terms of the licence.

The materials distributed with this unit may be freely copied and used by members of a single institution on a
single site only. You are not permitted to share in any way any of the materials or part of the materials with any
third party, including users on another site or individuals who are members of a separate institution. You
acknowledge that the materials must remain with you, the licencing institution, and no part of the materials may
be transferred to another institution. You also agree not to procure, authorise, encourage, facilitate or enable any
third party to reproduce these materials in whole or in part without the prior permission of PG Online Limited.

You might also like