Subroutines Flashcards
Why are subroutines used?
As your programs become larger and more complex, they need to be broken down into smaller, self-contained sections
Two types of subroutine used in programming:
Functions and procedures
What do subroutines allow you to do?
They 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
Are these subroutines functions or procedures:
print(“Hello)
input(“Type in your name: “)
random(1,6)
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
What are some examples of procedures
procedure showMenu()
print(“ Menu “)
print(“========================”)
print(“1: Play game”)
print(“2: Show key controls”)
print(“3: High scores”)
print(“4: Return to main menu”)
print(“5: Exit game”)
showMenu()
What are some examples of functions
Functions work just like procedures, except at the end they will return a value
function sum(a, b)
total = a + b
return total
endfunction
answer = sum(5, 3)
print(answer)
How can we pass parameters?
When you create a function with the statement:
sum(a, b)
a and b are known as parameters
e.g.
Create a function to calculate an average score
function averageScore(totalScore, numScores)
avg = totalScore / numScores
return avg
endfunction
List the advantages of subroutines
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
Subroutines can be stored in a subroutine library and used in different programs if required
Program maintenance is easier - if requirements changed then just the affected subroutines need to be modified
What is the “scope” of a variable
The “scope” of a variable, constant, procedure or function defines the parts of the program in which it is recognised and can be used
Explain the difference between a local and global variables
Globes are accessible anywhere in the program - locals only within the subroutine in which they were created
How many parameters can functions and procedures have?
Zero, one or many
What are three reasons that you should try to use subroutines where possible?
Reuse code, decomposition, more maintainable code