2.2.1 Programming Techniques Flashcards
Sequence
Code is executed line-by-line, from top to bottom
Branching (AKA Selection)
A certain block of code is run if a specific condition is met, using IF statements.
Iteration
A block of code is executed a certain number of times or while a condition is met. Uses FOR, WHILE or REPEAT UNTIL loops.
Count-controlled VS Condition-controlled
Count-controlled: Iteration is repeated a given number of times
Condition-controlled: Iteration continues until a given condition is met.
Recursion
A programming construct in which a subroutine calls itself during its execution. This continues until the stopping condition is met.
Advantages of recursion
Certain problems can be represented in fewer lines of code, making them less prone to errors.
Disadvantages of recursion
- Inefficient use of memory.
- Danger of stack overflow.
- Difficult to trace. This difficulty grows with more function calls.
Recursion relies on a stack, in order for it to work. Explain how recursion uses the call stack.
Each time the function calls itself, a new stack frame is created within the call stack.
A finite number of stack frames are created until the base case is reached. The subroutine unwinds, and begins to pop information off the stack
What do stack frames contain?
Parameters, local variables and return addresses.
Describe stack overflow during recursion
The call stack runs out of memory as a result of the subroutine calling itself too many times, causing the program to crash.
What does scope refer to?
The section of code in which the variable is available.
Local variables have limited scope. What does this mean?
They can only be accessed within the block of code in which they were defined.
Using local variables is considered good programming practice. Why?
It ensures subroutines are self contained, with no danger of variables being affected by code outside the subroutine.
Global variables can be accessed across the whole program. What is this useful for?
Values that need to be used by multiple parts of the program.
Why are global variables not recommended?
They can be unintentionally overwritten and edited. They also require more memory than local variables.