Algorithms & Flowcharts — Worked Examples
4. Making Decisions I
Making Decisions I
Real programs need to make choices. A decision asks a yes/no question and then takes one path or another. In a flowchart this is a diamond with two labelled arrows; in pseudocode and Python it is IF ... ELSE. Here are three worked examples.
Example (a): The larger of two numbers
Problem
Read two numbers and display whichever one is larger.
Pseudocode
START
INPUT a, b
IF a > b THEN
OUTPUT a
ELSE
OUTPUT b
END IF
END
Trace table
Sample input: a = 8, b = 5.
| Step | a | b | a > b ? | Output |
|---|---|---|---|---|
| INPUT a, b | 8 | 5 | — | — |
| IF a > b | 8 | 5 | 8 > 5 → Yes | — |
| OUTPUT a (Yes branch) | 8 | 5 | Yes | 8 |
In Python
a = int(input("Enter a: "))
b = int(input("Enter b: "))
if a > b:
print("The larger number is", a)
else:
print("The larger number is", b)
Output: (with a 8 and b 5)
The larger number is 8
Example (b): Positive, negative, or zero
Problem
Read a number and report whether it is positive, negative, or zero. This needs three outcomes, so we use two decisions.
Pseudocode
START
INPUT n
IF n > 0 THEN
OUTPUT "Positive"
ELSE IF n < 0 THEN
OUTPUT "Negative"
ELSE
OUTPUT "Zero"
END IF
END
Trace table
Sample input: n = -3.
| Step | n | n > 0 ? | n < 0 ? | Output |
|---|---|---|---|---|
| INPUT n | -3 | — | — | — |
| IF n > 0 | -3 | -3 > 0 → No | — | — |
| ELSE IF n < 0 | -3 | No | -3 < 0 → Yes | — |
| OUTPUT "Negative" | -3 | No | Yes | Negative |
In Python
n = int(input("Enter a number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")
Output: (with n -3)
Negative
Example (c): Even or odd
Problem
Read a whole number and report whether it is even or odd. A number is even when dividing it by 2 leaves no remainder. The remainder operator is mod (written % in Python).
Pseudocode
START
INPUT n
SET remainder = n mod 2
IF remainder = 0 THEN
OUTPUT "Even"
ELSE
OUTPUT "Odd"
END IF
END
Trace table
Sample input: n = 7.
| Step | n | remainder | remainder = 0 ? | Output |
|---|---|---|---|---|
| INPUT n | 7 | — | — | — |
| remainder = 7 mod 2 | 7 | 1 | — | — |
| IF remainder = 0 | 7 | 1 | 1 = 0 → No | — |
| OUTPUT "Odd" (No branch) | 7 | 1 | No | Odd |
In Python
n = int(input("Enter a whole number: "))
remainder = n % 2
if remainder == 0:
print(n, "is even")
else:
print(n, "is odd")
Output: (with n 7)
7 is odd