Menu

Writing and Refining Algorithms

Pseudocode

Pseudocode is a way of writing down an algorithm so that it looks like programming instructions, but is not tied to the exact syntax of any one programming language. It lets you concentrate on the logic, such as the order of the steps, the decisions and the repeats, without worrying about punctuation and spelling rules.

An algorithm can be recorded as pseudocode, or written straight away as program code in a high-level language such as Python.

Pseudocode must be precise

Pseudocode is not vague. It must be logically correct and precise enough for another programmer to turn it into program code. Each step should make clear what is input, stored, calculated, decided or output, and each decision should be written as a full comparison.

Python building blocks

When you convert an algorithm into Python, you use these building blocks:

  • input() and print() for input and output.
  • if, elif and else for selection.
  • for with range() for count-controlled iteration.
  • while for condition-controlled iteration.
  • a flag variable for a loop that must run at least once.

Because the computer runs your Python, every line must follow the rules of the language exactly; a computer cannot guess what a line was meant to say.

For example, to plan an algorithm that asks for a number and outputs whether it is positive, pseudocode lets you set the steps out in order: ask for the number, store it, decide whether it is greater than zero, then output a suitable message. In Python, the same algorithm has to be written using the exact rules of the language:

number = int(input("Enter a number: "))
if number > 0:
    print("Positive")
else:
    print("Not positive")

Output when the user types 7:

Enter a number: 7
Positive

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms