Pseudocode consists of the following:
n = 0
The right hand side can be made up of the usual operators, mathematical functions, calls to functions that are defined elsewhere in the pseudocode, and verbal descriptions that are unambiguous and can be turned into a line of code.
distance = sqrt(x2 + y2) ch = last character of str
You can use n++
or n += 1
as a shortcut for n = n + 1
, and similar for other compound assignment operators.
Don't use words “Set n to zero”—it's too wordy.
Don't differentiate between initialization and assignment. The first time that a variable is assigned to, it is implicitly declared. So, don't write “Create a variable n and initialize it with zero”—that's way too wordy.
Don't specify types. They should be clear from context, the name of the variable, or the initial value.
It's fine to use short variable names such as n
. You can also use variable names with spaces such as surface area
.
while in has more integers sum = sum + next integer count++
Use the familiar if
/while
/for in
structures.
for v in values sum += v count++
For iterating over an integer range, use
for i in 0 ... n - 1
Use indentation, not braces, for indicating nesting.
Append v to values Swap values[i] and values[j] Print sum / count
An action
An action can use the “function call” syntax if elsewhere in the pseudocode, or in the standard library, there is a function with that name. The function must update one or more parameters or generate output.
partition(a, from, to)
Always explicitly name the variable(s) that are affected by the action. Don't write “Swap them” or “Remove the element”, but make it clear what is swapped or what is removed from where.
An action can be “unfinished”, which means that you aren't quite sure yet how it will be implemented. Then add ... at the end. Examples:
Move all elements of a that are less than p before all elements ≥ p ...
Of course, you need to finish up all those statements before you are done.
//
notationFunction definitions consist of an underlined header with function name and parameter names, followed by an indented body.
partition(a, from, to, pivot)
i = from - 1;
j = to + 1;
while i < j
i++
while a[i] < pivot
i++
// Now a[i] ≥ pivot
j--
while a[j] > pivot
j--
// Now a[j] ≤ pivot
if i < j
swap a[i] and a[j]
return j
Don't write parameter or return types. Don't write throws
clauses.
Use return
to indicate a function return, just like in Java.