Video lecture
Watch on YouTube(opens in a new tab)Sub topic 8
Drawing Algorithms as Flowcharts
A flowchart draws an algorithm as a graph. Boxes hold actions, diamonds hold questions, and arrows show which step comes next. Pseudocode shows control flow through indentation and keywords. A flowchart makes it visible, so you can see every path through the algorithm, every point where paths split, and every place where control loops back.
This chapter assumes you can read simple Python and have seen the earlier chapters on sequence, selection and iteration and on pseudocode. Euclid's GCD algorithm runs through this chapter as the main example, as it does through the rest of the tutorial.
The Standard Symbols
Flowchart notation has a small vocabulary. The shapes below follow the common conventions descended from ISO 5807. Most textbooks and tools use them.
| Shape | Name | Meaning | Mermaid syntax |
|---|---|---|---|
| Rounded (stadium) | Terminal | Where the algorithm starts or stops | `S([Start])` |
| Parallelogram | Input/output | Reading inputs or producing outputs | `I[/"Read a, b"/]` |
| Rectangle | Process | One action, such as an assignment or calculation | `P["r = a mod b"]` |
| Diamond | Decision | A yes/no question; exactly two labelled exits | `D{"b = 0?"}` |
| Arrow | Flow line | Control passes from one shape to the next | `A --> B` |
The rules that make a flowchart unambiguous are short:
- There is exactly one Start terminal. Every path from it reaches a Stop terminal, unless the algorithm is deliberately non-terminating.
- Every process and input/output shape has exactly one outgoing arrow.
- Every decision has exactly two outgoing arrows, labelled with the two possible answers.
- An arrow may point back to an earlier shape. That backward arrow is how a loop appears.
These rules line up with the properties of an algorithm. A single outgoing arrow from each action gives definiteness, because there is never any doubt about what happens next. Labelled decision exits make every choice explicit. Reachable Stop terminals are where finiteness can fail, so they deserve a careful check.
Euclid's Algorithm as a Flowchart
Here is the plain-language version again, for comparison:
Euclid's algorithm (plain language)
Input: two non-negative integers a and b, not both zero.
Output: the greatest common divisor of a and b.
1. If b is 0, the answer is a. Stop.
2. Otherwise, compute r, the remainder of a divided by b.
3. Replace a with b, and b with r.
4. Go back to step 1.Each numbered step becomes one or more shapes. Step 1 becomes a decision. Steps 2 and 3 become process boxes. Step 4 ("go back") becomes an arrow that points back to the decision.
All three building blocks appear in this one picture:
- Sequence is the straight chain of three process boxes,
r = a mod b, thena = b, thenb = r. - Selection is the diamond and its two labelled exits.
- Iteration is the arrow from
b = rback up to the diamond. A loop is a cycle in the graph that passes through a decision. That decision is the only way out of the cycle.
The chart also shows a fact the plain-language version hides. The order inside the sequence matters. If you swap a = b and b = r, the chart is still well formed, but a would receive the remainder instead of the old b. Seeing three separate boxes in a fixed order shows you why a temporary variable r is needed. The Python version avoids the temporary with simultaneous assignment:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6Where the Test Sits: Pre-test and Post-test Loops
You can place a loop's decision in two places, and a flowchart shows clearly which one you chose.
- In a pre-test loop (
while), the decision comes before the body. The body may run zero times. Euclid's chart is a pre-test loop: ifbis 0 from the start, the body never runs. - In a post-test loop (
repeat ... until, ordo ... whilein C-like languages), the decision comes after the body. The body always runs at least once.
The difference matters for edge cases. Take counting the decimal digits of a non-negative integer n. The number 0 has one digit. A pre-test loop written as "while n > 0: divide by 10, add one" returns 0 for n = 0, which is wrong. A post-test loop gets it right because the body runs once before the first test.
Python has no post-test loop, so the idiom is while True with a break placed where the diamond sits:
def count_digits(n):
# Precondition: n is a non-negative integer
count = 0
while True:
count += 1
n //= 10
if n == 0:
break
return count
print(count_digits(0)) # 1
print(count_digits(4096)) # 4When you turn a flowchart into code, look at where the backward arrow lands compared with the decision. If it lands on the decision itself, the loop is a pre-test loop. If it lands on the first body box and the decision comes after the body, the loop is a post-test loop.
Multiple Exits: Linear Search
Some algorithms have more than one way to finish. Linear search stops early when it finds the target, or it stops after checking every item. A flowchart shows both exits as separate paths:
def linear_search(items, target):
for i, x in enumerate(items):
if x == target:
return i
return -1Python's for loop hides the counter, the bounds test and the increment. The flowchart has to show all three. This is useful when you count steps later. Each time round the loop costs one bounds test, one comparison and one increment, and the loop runs at most len(items) times.
Structured and Unstructured Flowcharts
Arrows can go anywhere, so a flowchart can describe control flow that no combination of if and while produces directly. Examples are a jump into the middle of a loop, or two loops that overlap without one nesting inside the other. Charts like this are called unstructured. They match goto-style code and are hard to reason about.
A structured flowchart is built only by combining the three building blocks:
| Block | Shape of the subgraph | Entries | Exits |
|---|---|---|---|
| Sequence | Boxes in a chain | 1 | 1 |
| Selection | Diamond, two branches, branches rejoin | 1 | 1 |
| Iteration | Diamond with a backward arrow | 1 | 1 |
Every block has one way in and one way out, so you can replace any process box with a whole block and the chart stays structured. The Böhm–Jacopini theorem (1966) says that any flowchart can be converted to a structured one, sometimes at the cost of extra flag variables. Early exits, like linear search's "Output i", break the strict one-exit rule. They are accepted in practice because they match return and break.
Common Errors
When to Use a Flowchart
Flowcharts work best for short algorithms with tangled branching, and for readers who think visually or don't program. They work badly for long algorithms. Charts grow fast and are hard to edit. They also have no standard way to show data structures, function calls or recursion. In practice, people sketch a flowchart to understand control flow, then write pseudocode or code as the lasting description. Text-based tools such as Mermaid narrow the gap, because the chart lives as source text you can keep under version control.
Exercise
Draw (in Mermaid or on paper) a flowchart for find_max, which takes a non-empty list xs and returns its largest element. Use an explicit index i. Is the loop pre-test or post-test, and what happens for a one-element list?
Show answer
Start -> Read xs -> best = xs[0] -> i = 1 -> decision "i < len(xs)?". No -> Output best -> Stop. Yes -> decision "xs[i] > best?"; Yes -> best = xs[i] -> i = i + 1; No -> i = i + 1; then the arrow from i = i + 1 goes back to the first decision. The loop is pre-test. For a one-element list, the first test (1 < 1) fails at once, the body never runs, and the chart outputs xs[0], which is correct.
Exercise
Someone redraws Euclid's flowchart and moves the "b = 0?" decision to after the three process boxes, so the body runs before any test. Give an input that meets the precondition but breaks this version, and explain why.
Show answer
Any input with b = 0, for example a = 5, b = 0. The body runs first and computes 5 mod 0, which is undefined (division by zero). The precondition allows b = 0, so the algorithm must test before dividing. That requires a pre-test loop.
Exercise
In the linear search flowchart, how many decision evaluations happen in the worst case for a list of length n, and when does the worst case occur?
Show answer
The worst case is when the target is absent. The bounds test "i < len(items)?" runs n + 1 times (n Yes answers, then one No), and the comparison "items[i] = target?" runs n times, for 2n + 1 decision evaluations in total. That count grows linearly with n.