Jan Mocks Flashcards
Recursion
When a subroutine calls itself within its own subroutine
A recursive subroutine should:
Contain a stopping condition (base case)
For any input value other than the stopping condition, the subroutine should call itself
The stopping condition should be reachable within a finite number of times
- without these characteristics a recursive subroutine may call itself indefinitely resulting in a stack overflow
Is recursion good
Recursion is not very memory efficient. Every time a recursive function calls itself the processor needs to remember where it was before it jumps to the new copy so it knows where to return later.
The processor also needs to remember the values of all the previous variables, as they are local to those copies of the recursive function- using stacks which takes up space in memory
Stack overflow
Recursive subroutines calls itself too many times before reaching its terminating condition you could run out of memory and cause the program to crash
When should you use recursion over iteration
Tree traversal algorithm
Performing a flood fill in a graphics application
Local variable accessibility
Single subroutine only
Local variable created
Declared inside a subroutine
Local variable destroyed
When the subroutine exits
Global variable accessibility
Entire program
Global variable created
Declared outside of a subroutine. Typically at the start of a program
Global variable destroyed
When the program ends
Local variable
Created when the subroutine is called
Global variable
Created when the program starts
Good program practice (g+l variables)
A system of passing in required values to the subroutine via parameters and returning values is considered safer and better programming practice
Why is overuse of global variables bad
Excessive, unnecessary use of global variables can make programs hard to test, debug and maintain
When should you use local variables
Should be used whenever possible
Modularity
The concept on breaking a large program or problem down into smaller chunks
Modularity goal
To design a program in a way that each module carries out single, specific task
What are modules also known as
Subroutine
Procedures
Functions
Methods
Procedure
Is a block of code that takes in zero, one or more parameters and performs a set task
Function
Block of code that takes in zero, one or more parameters, performs a set task, and returns a value
Return value
The return value from a function does not need to be assigned to a variable as long as it returns something valid
What does the interface outline
The name of the subroutine
The list of parameters it requires when it is called
The data type for those parameters
The order of those parameters
- if the subroutine interface is for a function, it also typically includes the data type of its return value
What does the first line of a subroutine specify
The interface for that subroutine