The Three Basic Constructs
| Construct | Purpose | Typical syntax |
|---|---|---|
| Sequence | Execute statements in fixed order | Straight line code |
| Branching (selection) | Choose path based on condition | IF / ELSEIF / CASE |
| Iteration | Repeat a block multiple times | FOR / WHILE / REPEAT UNTIL |
| Construct | Example behaviour |
|---|---|
| Sequence | Read name/age, then print messages in order |
| Branching | IF age-based message OR CASE day-name mapping |
| Iteration | FOR counter loop, WHILE password check, REPEAT-UNTIL guessing loop |
// Sequence
name = input("Enter name: ")
age = input("Enter age: ")
print("Hello " + name)
print("You are " + age + " years old")
// Branching
if age >= 18 then
print("You can vote")
elseif age >= 16 then
print("You can drive")
else
print("You are too young")
end if
switch day:
case 1: print("Monday")
case 2: print("Tuesday")
case 3: print("Wednesday")
default: print("Other day")
end switch
// Iteration
for i = 1 to 10:
print(i)
end for
while password != "secret" do
password = input("Enter password: ")
end while
repeat
guess = input("Guess the number: ")
until guess == targetNumber
Count-Controlled and Condition-Controlled Iteration
| Loop | Type of iteration | When the condition is tested | Fewest times the code inside runs |
|---|---|---|---|
| for | Count-controlled | No condition: it repeats a set number of times | Fixed by the start and end values |
| while | Condition-controlled, pre-condition | Before each pass | 0 |
| do-until (also written repeat-until) | Condition-controlled, post-condition | After each pass | 1 |