Sub-programs Flashcards
sub-program/subroutine
a self contained sequence of program instructions that performs a specific task
When are sub programs called?
whenever they need to carry out their specific function
uses of sub programs (5)
-allows the production of structured code
-makes programs shorter/more efficient
the code is written once and called as many times as needed
- program code is easier to read and test
- shortens development time of a program
- makes code more readable
function
a subroutine that returns a value to the main program when it is called
they have to be defined: function functionName(parameters) code return end function
procedure
a sub-program that carried out a specific task but does not return a value to the main program
they could do something such as print a message to the user
they have to be defined:
procedure procedureName(parameters)
code
endprocedure
parameters
where values passed to the function from the main program are stored
local variable
variables used within the subroutine and not in the main program
The following program included a sub program.
1 2 print("Hello " + first + " " + last) 3 // the following is the main program 4 name1 = input("Enter first name.") 5 name2 = (input("Enter surname") 6 salutation(name1, name2)
a) Complete the program by writing the code for:
i) line 1 [2]
ii) line 3 [1]
b) state one parameter used in the program [1]
a)
i) procedure salutation(first, last)
ii) endprodcedure
b) first or last
Write a subroutine that takes in a sentence entered by the user and returns the number of characters excluding spaces. [5]
function analysis(text) total = 0 for index = 0 to text.length - 1 if text(index) != " " then total = total + 1 endif next index return total endfunction
//main program sentence = input("Please enter the sentence.") characters = analysis(sentence) print(characters)
global variable
a variable used in the main program
should you use the same names for local and global variables?
no, as it would be easy to mix them up
The following is part of a program and a function to return the area of a rectangle.
function rectangle (length, width) area = length * width return area endfunction
//main program rectArea = rectangle(rectLength, rectWidth) print(rectArea)
a) List two global variables [2]
b) list two parameters [2]
c) state a local variable [1]
a) rectArea, rectLength, rectWidth
b) length, width
c) area
A student is creating a computer version of a board game during which each user has to shake two dice and find the total.
Create a function that will simulate the dice throws and return the total to the main program. [4]
(the random command is not in the OCR pseudocode, but any command that can be understood by a competent person can be used)
function dice() dice1 = random(1, 6) dice2 = random(1, 6) total = dice1 + dice2 return total endfunction