Pseudocode



index
Disabled back button Next Section
printable version

Section 1: How to write pseudocode

*Adapted from http://www.csc.calpoly.edu/~jdalbey/SWE/pdl_std.html

Pseudocode is a kind of structured English for describing algorithms.

In general, the vocabulary used in the pseudocode should be the vocabulary of the problem domain, not of the implementation domain.

Note that the logic must be decomposed to the level of a single loop or decision.

Each textbook and each individual designer may have their own personal style of pseudocode.

The "structured" part of pseudocode is a notation for representing six specific structured programming constructs: SEQUENCE, WHILE, IF-THEN-ELSE, REPEAT-UNTIL, FOR, and CASE.

It has been proven that three basic constructs for flow of control are sufficient to implement any "proper" algorithm.

Although these constructs are sufficient, it is often useful to include three more constructs:

Section 2: Construct Details

SEQUENCE

Sequential control is indicated by writing one action after another, each action on a line by itself, and all actions aligned with the same indent.

Example

READ height of rectangle
READ width of rectangle
COMPUTE area as height times width

Common Action Keywords – Several keywords are used to indicate common input, output, and processing operations.


IF-THEN-ELSE

Binary choice on a given Boolean condition is indicated by the use of four keywords: IF, THEN, ELSE, and ENDIF. The general form is:

IF condition THEN
   sequence 1
ELSE
   sequence 2
ENDIF

The ELSE keyword and "sequence 2" are optional.

Example

IF HoursWorked > NormalMax THEN
   Display overtime message
ELSE
   Display regular time message
ENDIF


WHILE

The WHILE construct is used to specify a loop with a test at the top, and the beginning and ending of the loop are indicated by two keywords WHILE and ENDWHILE. The general form is:

WHILE condition
   sequence
ENDWHILE

The loop is entered only if the condition is true.

Example

WHILE Population < Limit
   Compute Population as Population + Births - Deaths
ENDWHILE

Example

WHILE employee.type NOT EQUAL manager AND personCount < numEmployees
   INCREMENT personCount
   CALL employeeList.getPerson with personCount RETURNING employee
ENDWHILE


CASE

A CASE construct indicates a multiway branch based on conditions that are mutually exclusive.

The general form is:

CASE expression OF
   condition 1 : sequence 1
   condition 2 : sequence 2
   ...
   condition n : sequence n
   OTHERS : default sequence
ENDCASE

The OTHERS clause with its default sequence is optional.

Example

CASE Title OF
   Mr: Print "Mister"
   Mrs: Print "Missus"
   Miss: Print "Miss"
   Ms: Print "Mizz"
   Dr: Print "Doctor"
ENDCASE

Example

CASE grade OF
   A: points = 4
   B: points = 3
   C: points = 2
   D: points = 1
   F: points = 0
ENDCASE


REPEAT-UNTIL

This loop is similar to the WHILE loop except that the test is performed at the bottom of the loop instead of at the top. Two keywords, REPEAT and UNTIL are used. The general form is:

REPEAT
   sequence
UNTIL condition

The "sequence" in this type of loop is always performed at least once, because the test is performed after the sequence is executed.


FOR

This loop is a specialized construct for iterating a specific number of times, often called a "counting" loop. Two keywords, FOR and ENDFOR are used. The general form is:

FOR iteration bounds
   sequence
ENDFOR

In cases where the loop constraints can be obviously inferred it is best to describe the loop using problem domain vocabulary.

Example

FOR each month of the year (good)
FOR month = 1 to 12 (ok)

FOR each employee in the list (good)
FOR empno = 1 to listsize (ok)


NESTED CONSTRUCTS

The constructs can be embedded within each other, and this is made clear by use of indenting. Nested constructs should be clearly indented from their surrounding constructs.

Example

SET total to zero
REPEAT
   READ Temperature
   IF Temperature > Freezing THEN
      INCREMENT total
   END IF
UNTIL Temperature < zero
Print total

In the above example, the IF construct is nested within the REPEAT construct, and therefore is indented.


INVOKING SUBPROCEDURES

Use the CALL keyword. For example:

CALL AvgAge with StudentAges
CALL Swap with CurrentItem and TargetItem
CALL Account.debit with CheckAmount
CALL getBalance RETURNING aBalance


EXCEPTION HANDLING

BEGIN
   statements EXCEPTION
   WHEN exception type
      statements to handle exception
   WHEN another exception type
      statements to handle exception
END

Section 3: Examples

Adequate

FOR X = 1 to 10
   FOR Y = 1 to 10
      IF gameBoard[X][Y] = 0
         Do nothing
      ELSE
         CALL theCall(X, Y) (recursive method)
         increment counter
      END IF
   END FOR
END FOR

Better – the logic is restructured to omit the "do nothing" clause

Set moveCount to 1
FOR each row on the board
   FOR each column on the board
      IF gameBoard position (row, column) is occupied THEN
         CALL findAdjacentTiles with row, column
         INCREMENT moveCount
      END IF
   END FOR
END FOR


Not So Good

FOR all the number at the back of the array
   SET Temp equal the addition of each number
   IF > 9 THEN
      get the remainder of the number divided by 10 to that index and carry the "1"
   Decrement one
Do it again for numbers before the decimal

Good Enough (not perfect)

SET Carry to 0
FOR each DigitPosition in Number from least significant to most significant

   COMPUTE Total as sum of FirstNum[DigitPosition] and SecondNum[DigitPosition] and Carry

   IF Total > 10 THEN
      SET Carry to 1
      SUBTRACT 10 from Total
   ELSE
      SET Carry to 0
   END IF

   STORE Total in Result[DigitPosition]

END LOOP

IF Carry = 1 THEN
   RAISE Overflow exception
END IF


Pretty Good – this example shows how pseudocode is written as comments in the source file. Note that the double slashes are indented.

public boolean moveRobot (Robot aRobot)
{
   //IF robot has no obstacle in front THEN
      // Call Move robot
      // Add the move command to the command history
      // RETURN true
   //ELSE
      // RETURN false without moving the robot
   //END IF
}

Example JavaScript Implementation

function moveRobot(aRobot)
{
   // IF robot has no obstacle in front THEN
   if (aRobot.isFrontClear())
   {
      // Call Move robot
      aRobot.move();
      // Add the move command to the command history
      cmdHistory.add(RobotAction.MOVE);
      return true;
   }
   else // don't move the robot
   {
      return false;
   }
}