Programs in imperative languages are sequences of instructions. The next instruction to execute is the one that follows in the text of the program unless some sort of control statement is used.
Control Statements in imperative languages incl.:
- selection constructs
- iterative constructs
- branching instructions
Any sequential algorithm can be created using just a selection (if-else) and logically controlled iteration (while).
Selection Constructs
Choose between two or more execution paths in a program.
Two-way selector (if-else)
if (x):
result = 1
else:
result = 0Multiple selector (generalisation of two-selector)
switch (expr):
case a:
result = 1
case b:
result = 2
default:
result = 0Iterative Constructs
Iterative constructs cause a statement or sequence of statements to be repeated.
A pre-test loop is where the test for loop completion is done before the execution. A post-test loop is where the test for loop completion is done after the execution.
Counter-controlled loop
for (index = 0; index < 10; index++):
print(index)Logically-controlled loop
while (expr):
print('do something')Program Structure
A block is a group of statements, delimited by keywords such as begin and end, or by separators such as { and }. Block may contain not only commands but also declarations.
If the language has static scope, these declarations will only be visible within this block if they are local variables.
Subprogram is a generic name for a named block that can be invoked explicitly. In this case the block of statements is executed upon invocation. Control returns to calling point after execution.
- Can be declared with parameters.
- When invoked, associated parameters are actual parameters.