Contents Previous Next Subchapters

Using Recursion
See Also forward , for , while , goto

Description
A recursive function references itself. The following function uses recursion to calculate the factorial of a number.
     clear
     function factorial(n) begin
          if n==1 then return 1
          return n * factorial(n - 1)
     end
If you then enter the text above followed by
     print factorial(3)
O-Matrix will respond
     6
The reference factorial(3) caused the following evaluations:
     function factorial(3) begin
          if 3==1 then return 1
          return 3 * factorial(2) # factorial(2) returns 2*1
     end
     function factorial(2) begin
          if 2==1 then return 1
          return 2 * factorial(1) # factorial(1) returns 1
     end
     function factorial(1) begin
          if 1==1 then return 1   # returns 1
          return 1 * factorial(0)
     end