The control-flow structures that make programs actually make decisions and repeat work — the true engine of every algorithm you'll write.
Selection structures (making decisions):
| Structure | Use when |
|---|---|
| if | One condition, one action if true |
| if … else | Two possible outcomes, only one branch runs |
| switch / case | Choosing between many specific, discrete values of one variable — often cleaner than a long if/else chain |
Example
int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Another day"); }
Nested selection (if / else if / else) as a flowchart — only one path is ever taken.
Looping structures (repeating actions):
| Loop | Best for | Check timing |
|---|---|---|
| for | A known/counted number of repetitions | Pre-check (condition tested before each iteration) |
| while | An unknown number of repetitions, based on a condition | Pre-check (may run zero times if condition starts false) |
| do … while | When the loop body must run at least once | Post-check (condition tested after each iteration) |
| repeat … until | Similar to do-while conceptually (used in pseudocode) | Post-check |
Choosing for vs while: use a counting loop (for) when you know exactly how many times to repeat; use a condition loop (while) when repetition depends on something happening (e.g. user input, a value being found).
Classic algorithms you must be able to code from scratch:
Example
// Swapping two values needs a temporary variable int temp = a; a = b; b = temp;
Nested selection and nested loops — a selection statement or loop placed entirely inside another. Each nested loop needs its own independent counter variable.
Use methods to abstract away complex nested logic — wrapping a complicated nested loop in a well-named method makes the calling code far more readable, which also improves code efficiency by avoiding duplication if that logic is needed more than once.
💡 Exam Tip
For 'isolating digits' problems: `number % 10` gives the last digit, and `number / 10` (integer division) removes that last digit, ready to repeat for the next digit.