Back to table

A program that calculates factorials

The following is a valid µOCCAM program that performs I/O. The program will calculate and return the factorial of a number that is entered as input. (Note that 0 is returned if the input is negative) The program makes use of a number of different constructions.

Program file: /public/cs3/web/ipptests/factorial.io

-- This program takes a number from standard input and returns
-- the factorial of this number to standard output.
-- Note that 0 is returned for a negative input.

INT factorial:
INT result=0:
SEQ
  stdin ? factorial -- input factoral value to be calculated
  IF
    factorial >= 0
      result := 1
  WHILE factorial > 0
    SEQ
      result := (result * factorial)
      factorial := (factorial-1)
  stdout ! result

When provided with this input: /public/cs3/web/ipptests/factorial.in

4

it should generate the following output: /public/cs3/web/ipptests/factorial.out

==> 24