MarzleyTech Learn

Home / Learn / Algorithms & problem solving / Pseudocode and flowcharts: algorithms explained, sequence, selection, iteration, trace tables and turning plans into code

Pseudocode and flowcharts: algorithms explained, sequence, selection, iteration, trace tables and turning plans into code

An algorithm is a precise, step-by-step set of instructions for solving a problem. You follow algorithms every day: a recipe for chapati, directions to a matatu stage, the steps to send money on M-Pesa. Computers need algorithms written so clearly that there is no guesswork. Before writing code, programmers often plan with pseudocode (structured plain-language steps) and flowcharts (diagrams). These are tested in KCSE Computer Studies, CBC, university courses and job interviews, and they make you a much better programmer in any language.

What makes a good algorithm?

PropertyMeaning
PreciseEach step is clear and unambiguous
FiniteIt finishes after a limited number of steps
CorrectIt gives the right output for all valid inputs
Has inputs and outputsTakes data in, produces a result
EfficientDoesn't waste time or memory (see Big O)

Input, process, output (IPO)

Before designing, identify:

InputsProcessOutputs
Price and quantitytotal = price × quantity; add VATTotal to pay
Student marksCalculate average; decide gradeAverage and grade

The three building blocks

Every algorithm is built from:

  1. Sequence: steps one after another.
  2. Selection: decisions (IF... THEN... ELSE).
  3. Iteration: repetition (loops: FOR, WHILE, REPEAT UNTIL).

Pseudocode conventions

There's no single official standard, but common conventions are:

START
  INPUT price
  INPUT quantity
  total ← price * quantity
  IF total > 5000 THEN
      discount ← total * 0.05
  ELSE
      discount ← 0
  ENDIF
  OUTPUT total - discount
STOP
KeywordMeaning
INPUT / READGet data
OUTPUT / PRINT / DISPLAYShow results
← or = or SETAssign a value
IF ... THEN ... ELSE ... ENDIFSelection
CASE ... OFMultiple choices
FOR i ← 1 TO 10 ... ENDFORCounted loop
WHILE condition DO ... ENDWHILELoop while true (checked first)
REPEAT ... UNTIL conditionLoop at least once

Indent the inside of IFs and loops so structure is clear.

Flowchart symbols

SymbolShapeMeaning
TerminatorRounded rectangle (oval)Start / Stop
ProcessRectangleCalculation or action (total = price × qty)
Input/OutputParallelogramRead input or display output
DecisionDiamondA yes/no question with two exits
Flow lineArrowDirection of flow
ConnectorSmall circleConnects parts of a large flowchart
Predefined processRectangle with side barsA subroutine/function

A flowchart for Pass/Fail:

   ( Start )
       |
  / Input score /
       |
   < score >= 50 ? >
     yes /    \ no
  / Output Pass / / Output Fail /
        \       /
        ( Stop )

Draw neat flowcharts with free tools like draw.io (diagrams.net) or Lucidchart.

Example 1: Grade calculator (selection)

Pseudocode:

INPUT mark
IF mark >= 80 THEN grade ← "A"
ELSE IF mark >= 65 THEN grade ← "B"
ELSE IF mark >= 50 THEN grade ← "C"
ELSE IF mark >= 40 THEN grade ← "D"
ELSE grade ← "E"
ENDIF
OUTPUT grade

Python:

Python · runs live in the interactive lesson
def grade(mark):
    if mark >= 80:
        return "A"
    elif mark >= 65:
        return "B"
    elif mark >= 50:
        return "C"
    elif mark >= 40:
        return "D"
    return "E"

for m in [91, 70, 55, 42, 18]:
    print(m, grade(m))

Notice the order matters: checking >= 50 before >= 80 would give a mark of 91 a C.

Example 2: Totals and averages (iteration)

total ← 0
FOR i ← 1 TO 5
    INPUT mark
    total ← total + mark
ENDFOR
average ← total / 5
OUTPUT average
Python · runs live in the interactive lesson
marks = [67, 82, 45, 90, 58]    # instead of typing inputs
total = 0
for mark in marks:
    total = total + mark
average = total / len(marks)
print("Total:", total, "Average:", average)

Example 3: Largest number

largest ← first number
FOR each remaining number n
    IF n > largest THEN largest ← n
ENDFOR
OUTPUT largest
Python · runs live in the interactive lesson
numbers = [34, 78, 12, 95, 60]
largest = numbers[0]
for n in numbers[1:]:
    if n > largest:
        largest = n
print("Largest:", largest)

Example 4: A tiered charge (like transaction fees)

Many systems charge fees by bands. With made-up example bands:

INPUT amount
IF amount <= 100 THEN fee ← 0
ELSE IF amount <= 1000 THEN fee ← 15
ELSE IF amount <= 5000 THEN fee ← 30
ELSE fee ← 50
ENDIF
OUTPUT fee
Python · runs live in the interactive lesson
def fee(amount):
    # example bands for learning, not real M-Pesa tariffs
    if amount <= 100:
        return 0
    elif amount <= 1000:
        return 15
    elif amount <= 5000:
        return 30
    return 50

for a in [50, 100, 101, 2500, 20000]:
    print(f"KSh {a:>6}: fee KSh {fee(a)}")

Testing the boundaries (100, 101, 1000, 1001) is where most bugs hide.

WHILE vs REPEAT UNTIL

  • WHILE checks the condition first (may run zero times).
  • REPEAT ... UNTIL runs at least once (useful for menus and input validation).
REPEAT
    INPUT pin
UNTIL pin is 4 digits

Python has no REPEAT UNTIL, so we use while True with break:

Python · runs live in the interactive lesson
attempts = ["12", "abcd", "4821"]     # simulated user inputs
i = 0
while True:
    pin = attempts[i]
    i += 1
    print("Entered:", pin)
    if len(pin) == 4 and pin.isdigit():
        break
print("Valid PIN entered after", i, "attempts")

Trace tables

A trace table tests an algorithm by hand, recording variable values at each step. Trace the totals algorithm with marks 10, 20, 30:

StepmarktotalOutput
Start–0
11010
22030
33060
Endaverage = 20

Trace tables catch logic errors before you code, and exam questions often ask you to complete them.

From plan to code

  1. Understand the problem (IPO).
  2. Write pseudocode or draw a flowchart.
  3. Trace with sample data, including edge cases (0, negative, maximum, empty).
  4. Translate line by line into Python (or any language).
  5. Test with the same data and compare.
Think about it: Write pseudocode for: "Read the prices of items until the user enters 0, then output the total and the number of items."Show answer
total ← 0
count ← 0
INPUT price
WHILE price <> 0 DO
    total ← total + price
    count ← count + 1
    INPUT price
ENDWHILE
OUTPUT total, count

The 0 is a sentinel value that ends the loop and isn't counted.

Summary

  • An algorithm is a precise, finite, correct set of steps with inputs and outputs.
  • All algorithms combine sequence, selection (IF/CASE) and iteration (FOR, WHILE, REPEAT UNTIL).
  • Pseudocode uses INPUT, OUTPUT, assignment, IF/ENDIF and loops with indentation; flowcharts use ovals, rectangles, parallelograms, diamonds and arrows.
  • Trace tables test algorithms by hand, especially at boundaries.
  • Plan with IPO and pseudocode, trace, then translate to code and test.

Check yourself

  1. Which flowchart symbol is used for a decision?

    Show answer

    diamond

  2. Which flowchart symbol is used for input and output?

    Show answer

    parallelogram

  3. Which loop always runs at least once: WHILE or REPEAT UNTIL?

    Show answer

    REPEAT UNTIL

  4. What are the three basic building blocks of algorithms? (three words)

    Show answer

    sequence selection iteration

  5. What table tracks variable values step by step to test an algorithm? (two words)

    Show answer

    trace table

  6. A special value like 0 that ends an input loop is called a what?

    Show answer

    sentinel

Exercise

Write code that prints Pass if score is 50 or more, otherwise Fail. Test it with score = 72.

Do this exercise in the live editor

Lesson 1 of 11 in Algorithms & problem solving · Written by · Course notes