Writing Algorithms - Pseudocode

Writing Algorithms - Pseudocode

Introduction to Pseudocode

  • Pseudocode is a simplified, plain English approach to writing code.
  • It is not an actual programming language, hence is not executable on a computer.
  • The key purpose is to model and communicate an algorithm in a human-readable format.
  • It helps programmers concentrate on the problem-solving process rather than the syntax of a specific programming language.

Key Principles of Writing Pseudocode

  • Express the algorithm step by step, in line with the flow of execution.
  • Use consistent notation, which although not standardised, should be clear and easy to understand.
  • Include flow of control mechanisms like IF, WHILE, FOR, etc.
  • Incorporate data structures such as lists, arrays, etc., when necessary.
  • Use indentation to show blocks of code under procedures, loops, conditional statements, etc.

Example of Pseudocode

An example can be written for calculating the factorial of a number n:

PROCEDURE factorial (n)
   IF n IS EQUAL TO 0
       THEN RETURN 1
   ELSE
       RETURN n * factorial(n-1)
   ENDIF
ENDPROCEDURE

Decomposing Problems in Pseudocode

  • Use decomposition to break down complex problems into manageable parts. Think of each part being a function or a procedure in your pseudocode.
  • Each decomposed part can be tackled individually and expressed in pseudocode.
  • Use recursion, a function calling itself, for a more concise representation when suitable.

Pseudocode for Basic Data Structures

  • Arrays: These can be represented with brackets [] and can be one-dimensional (a list) or multi-dimensional (a table or grid).
  • Records: These can be visualised as a row of a database table, containing different fields.
  • Stacks and Queues: These are advanced data structures that can be modelled using pseudocode. Just remember: Stacks are Last-In-First-Out (LIFO) structures and Queues are First-In-First-Out (FIFO) structures.

Evaluating Pseudocode

  • Always check the logic and the flow - does the pseudocode accurately represent the problem and solve it correctly?
  • Could the pseudocode be optimised or made more efficient? This could involve using different logic, or reusing common calculations via functions.
  • As long as the pseudocode can be understood by another person, you’ve achieved your goal! Remember, pseudocode is meant to help us think through our algorithms before worrying about the technicalities of coding.