CIE AS & A Level Computer Science, section 20.1 (Programming paradigms)
What imperative programming is
In the imperative paradigm, a program is a sequence of statements that tell the computer how to solve the problem, step by step. Statements change the program's state (the values of its variables).
Building blocks
- Sequence: statements run in order.
- Selection:
IFandCASE. - Iteration:
FOR,WHILE,REPEAT. - Procedures and functions to structure the code (procedural programming).
- Variables and assignment.
Languages such as Python, Pascal, C and Visual Basic can be used in this way. It is the style used throughout sections 9 to 12.
Example
def average(marks):
total = 0 # state
for m in marks: # iteration
total = total + m # the state changes
return total / len(marks)
def report(marks):
avg = average(marks)
if avg >= 50: # selection
print("Pass", avg)
else:
print("Fail", avg)
report([60, 45, 72]) # Pass 59.0
Benefits
- Easy to follow, because the steps match the order they run.
- Efficient, as it maps well on to how the processor works.
- Programs can be divided into procedures.
Drawbacks
- Larger programs are harder to manage and changes in one place may break others, especially with global variables.
- Not as good as other paradigms for modelling real-world objects (object-oriented) or for logic problems (declarative).
Comparing
| Imperative | |
|---|---|
| Describes | how to do it |
| Main idea | sequence of statements changing state |
| Typical unit | procedure or function |
Common mistake: thinking imperative programming means "no objects". A program using objects is still imperative inside its methods. The key point is that it gives step-by-step instructions. Also, global variables make changes of state hard to track.
Exam tip: describe imperative programming as a sequence of instructions that change the state, and give an example using sequence, selection and iteration.
Check yourself
What does "state" mean in an imperative program?
The current values of the program’s variables.
Identify three programming constructs used in imperative programs.
Sequence, selection and iteration (also procedures and functions).
Give one drawback of imperative programming in a large program.
It is harder to manage, as changes in one part can affect others, especially through global variables.