The order of instructions matters because a program normally executes statements one after another, and each statement can change the data used by later statements. Changing the order can therefore change the output, cause an error, or alter the program's behavior.
How sequential execution works
Sequence is a fundamental programming construct in which instructions are executed in their written order. During execution, variables and other stored data form the program's state. Each instruction may read the current state, modify it, or produce output.
For example:
score = 5
score = score + 3
OUTPUT score
This outputs 8 because score is updated before it is displayed. If OUTPUT score is moved before the update, the output is 5. If the initialization score = 5 is moved after the calculation, the program may produce an error because score is used before it has been assigned a value.
The normal sequence can also be changed deliberately by other programming constructs:
| Construct | Effect on instruction order |
|---|---|
| Sequence | Executes statements from one instruction to the next. |
| Selection | Chooses which instructions execute based on a Boolean condition. |
| Iteration | Repeats instructions while or until a condition is met, or for a specified number of times. |
| Procedure or function call | Transfers control to another block of instructions before returning. |
A common misconception is that a computer understands the overall intention of an algorithm and rearranges instructions appropriately. It does not: it follows the defined control flow, including any dependencies and side effects created by earlier instructions.
IB exam technique
In B2.3 Programming constructs, you may be asked to trace an algorithm or determine its output. Work through statements in execution order, recording every variable update in a trace table. Pay particular attention to initialization, selection conditions, loop updates, and output statements.