Algorithms & Flowcharts — Worked Examples

3. Sequential Algorithms (no decisions, no loops)

Sequential Algorithms (no decisions, no loops)

A sequential algorithm is the simplest kind: the steps run one after another, top to bottom, with no questions to answer and nothing to repeat. If you can list the steps in order, you can write a sequential algorithm. Here are three worked examples.

Example (a): Area & perimeter of a rectangle

Problem

Read the length and width of a rectangle, then calculate and display its area and perimeter.

Start READ length, width area = length × width perimeter = 2 × (length + width) PRINT area, perimeter End

Pseudocode

START
  INPUT length
  INPUT width
  SET area = length * width
  SET perimeter = 2 * (length + width)
  OUTPUT area
  OUTPUT perimeter
END

Trace table

Sample input: length = 5, width = 3.

Steplengthwidthareaperimeter
INPUT length5———
INPUT width53——
area = 5 × 35315—
perimeter = 2 × (5 + 3)531516
OUTPUT531516

In Python

length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = length * width
perimeter = 2 * (length + width)
print("Area:", area)
print("Perimeter:", perimeter)

Output: (with length 5 and width 3)

Area: 15.0
Perimeter: 16.0

Example (b): Celsius → Fahrenheit converter

Problem

Read a temperature in degrees Celsius and convert it to degrees Fahrenheit using the formula F = C × 9/5 + 32.

Start READ celsius fahrenheit = celsius × 9/5 + 32 PRINT fahrenheit End

Pseudocode

START
  INPUT celsius
  SET fahrenheit = celsius * 9 / 5 + 32
  OUTPUT fahrenheit
END

Trace table

Sample input: celsius = 100.

Stepcelsiusfahrenheit
INPUT celsius100—
fahrenheit = 100 × 9 / 5 + 32100180 + 32 = 212
OUTPUT fahrenheit100212

In Python

celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32
print(celsius, "C =", fahrenheit, "F")

Output: (with celsius 100)

100.0 C = 212.0 F

Example (c): Swap the values of two variables

Problem

Read two values, then swap them so the first holds what the second had, and the second holds what the first had.

The trick is a temporary variable. If you just wrote a = b then b = a, the first value of a would be lost. So we park it in temp first.

Start READ a, b temp = a a = b b = temp PRINT a, b End

Pseudocode

START
  INPUT a, b
  SET temp = a
  SET a = b
  SET b = temp
  OUTPUT a, b
END

Trace table

Sample input: a = 7, b = 4.

Stepabtemp
INPUT a, b74—
temp = a747
a = b447
b = temp477
OUTPUT a, b477

In Python

a = int(input("Enter a: "))
b = int(input("Enter b: "))
temp = a
a = b
b = temp
print("a =", a, "  b =", b)

Output: (with a 7 and b 4)

a = 4   b = 7

(Python also offers a one-line shortcut, a, b = b, a, but the temp version shows exactly what is happening.)