Programming Constructs
IB Syllabus: B2.3 - Programming constructs
Overview
Every program - no matter how complex - is built from just three fundamental constructs:
| Construct | What it does | Syllabus |
|---|---|---|
| Sequence | Instructions execute one after another, in order | B2.3.1 |
| Selection | A decision is made - different paths based on a condition | B2.3.2 |
| Iteration | A block of code repeats while a condition holds | B2.3.3 |
| Methods & Modularization | Named, reusable blocks of code + scope (local vs global) | B2.3.4 |
Sequence
Sequence is the default. Lines of code execute from top to bottom, exactly as written.
int a = 5; // line 1
int b = 3; // line 2 - runs after line 1
int sum = a + b; // line 3 - runs after line 2
System.out.println("Sum: " + sum); // line 4
The order matters. Swapping lines 1 and 3 would cause an error because a is not yet defined.
Choosing the Right Loop
| Situation | Best loop |
|---|---|
| Known number of repetitions (e.g., 1 to 10) | for |
| Repeat while a condition holds; may not run at all | while |
| Must run at least once (e.g., input validation) | do-while |
| Traversing a 2D structure | Nested for |