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.
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.
| Step | length | width | area | perimeter |
|---|---|---|---|---|
| INPUT length | 5 | — | — | — |
| INPUT width | 5 | 3 | — | — |
| area = 5 × 3 | 5 | 3 | 15 | — |
| perimeter = 2 × (5 + 3) | 5 | 3 | 15 | 16 |
| OUTPUT | 5 | 3 | 15 | 16 |
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.
Pseudocode
START INPUT celsius SET fahrenheit = celsius * 9 / 5 + 32 OUTPUT fahrenheit END
Trace table
Sample input: celsius = 100.
| Step | celsius | fahrenheit |
|---|---|---|
| INPUT celsius | 100 | — |
| fahrenheit = 100 × 9 / 5 + 32 | 100 | 180 + 32 = 212 |
| OUTPUT fahrenheit | 100 | 212 |
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.
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.
| Step | a | b | temp |
|---|---|---|---|
| INPUT a, b | 7 | 4 | — |
| temp = a | 7 | 4 | 7 |
| a = b | 4 | 4 | 7 |
| b = temp | 4 | 7 | 7 |
| OUTPUT a, b | 4 | 7 | 7 |
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.)