Chapter 56 - Subroutines and recursion Flashcards
What is a subroutine?
» A name block of code which performs a specific task within a program
What are the 2 types of subroutines?
» Functions
» Procedures
What is the difference between a function and a procedure?
» The function returns a value but the procedure doesn’t
» if there are values already in the subroutine, you use a procedure
How can you call the subroutine from the main program and output it to the user?
» Simply write the subroutine name
What does the first line of a subroutine specify?
» The interface for that subroutine
What is modularity?
» Concept of breaking a large program or problem down into smaller chuncks
What is the benefit of modularity?
» Each module carries out a single specific task
What does a procedure do?
» Performs a set task and can take in a zero, 1 or 2 inputs
What happens when a parameter is passed by a value?
» The value created for the subroutine being called is a copy of the original
» Held in a separate memory location once passed
» It is now a local variable
What happens if you change the parameter inside the subroutine when you pass a value?
» It will not affect its value outside the subroutine
What does it mean if a parameter is passed by a reference?
» The address of the parameter is passed to the subroutine
» A pointer that contains the memory address of the original variable is created
What happens if you change the value in the parameter when passing by a reference?
» A change to this value within the called subroutine will also affect the value outside the subroutine
» It becomes a global variable
What does it mean if you say a scope of a variable?
» Refers to where a variable is visible or accessible from inside the main program
What is a global variable?
» A variable which is defined in the main program, outside any functions
» Has a global scope
What are some disadvantages of using a global variable?
» Needs to be preserved in memory all the time, this means memory space is kept throughout the running of the program
» Makes it less memory efficient
Why do we avoid using global variables?
» Increases complexity of the program - as they can be used by many difference parts of the program
» Make them harder to keep track of its value
» If you want to re-use code, you have to track and remember the value of the global variable
Why do we used global variables?
» To use a variable which can be accessed from any parts of a program
» When a value needs to stay the same throughout the program
What is a local variable?
» A variable which is defined in the procedure or function, and can be used only inside that function
What are the advantages of using a local variable?
» Local variables in difference subroutines can have the same identifier
» Changing the value of a local variable in a subroutine, will not affect its value outside the subroutine