Code of the Day
BeginnerMental Models

Logic and control flow

The three universal shapes — sequence, selection, iteration — from which all logic is built.

FundamentalsBeginner9 min read
Recommended first
By the end of this lesson you will be able to:
  • Identify the three building blocks of all program logic
  • Reason about boolean conditions and combine them safely
  • Explain how a loop is guaranteed to end (and why some don't)

Here's a quietly profound fact: every program ever written is built from just three shapes of control flow. Master these and you can express any in any language — the syntax is just decoration on top.

Shape 1 — Sequence

The default: one instruction after another, top to bottom. Order matters, because each step can depend on the state left by the previous one.

heat the pan
add the oil
add the egg

Swap two of those and you get a different (worse) result. Programs are the same.

Shape 2 — Selection

Doing different things depending on a condition — if / else:

if the user is logged in:
    show the dashboard
else:
    show the login page

Conditions are boolean expressions: they evaluate to true or false. You combine them with and, or, and not. Two habits prevent most bugs here:

  • Make conditions readableif age >= 18 beats a cryptic flag.
  • Watch the boundaries — is it > or >=? Off-by-one errors love if.

Shape 3 — Iteration

Repeating work — loops. Two flavours:

  • Definite (for): repeat once per item in a collection, or a fixed number of times. "For each order, send a receipt."
  • Indefinite (while): repeat as long as a condition holds. "While there are unread messages, process the next one."

Every loop needs a reason to stop. A for over a finite collection stops naturally. A while only stops if something inside it eventually makes the condition false — miss that and you have an infinite loop.

Whenever you write a while loop, point at the specific line that moves it toward stopping. If you can't, you've probably written an infinite loop.

Composing the three

Real logic nests these shapes: a loop containing an if, inside another loop. That's it — there is no fourth shape. When code feels overwhelming, find the sequences, selections, and iterations and it resolves into something you can follow.

Where to go next

Once logic grows, you tame it by decomposition — breaking it into named, reusable pieces. That's next.

Finished reading? Mark it complete to track your progress.

On this page