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.

Start READ a, b a > b ? Yes No PRINT a PRINT b End

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.

Stepaba > b ?Output
INPUT a, b85——
IF a > b858 > 5 → Yes—
OUTPUT a (Yes branch)85Yes8

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.

Start READ n n > 0 ? Yes PRINT "Positive" No n < 0 ? Yes PRINT "Negative" No PRINT "Zero" End

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.

Stepnn > 0 ?n < 0 ?Output
INPUT n-3———
IF n > 0-3-3 > 0 → No——
ELSE IF n < 0-3No-3 < 0 → Yes—
OUTPUT "Negative"-3NoYesNegative

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).

Start READ n remainder = n mod 2 remainder = 0 ? Yes No PRINT "Even" PRINT "Odd" End

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.

Stepnremainderremainder = 0 ?Output
INPUT n7———
remainder = 7 mod 271——
IF remainder = 0711 = 0 → No—
OUTPUT "Odd" (No branch)71NoOdd

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