Liberty BASIC Help Online |
Recursion
Liberty BASIC supports recursive subroutine and function calls. This means that a function can call itself. When it does this it makes a copy of itself, reusing its variable names. The values are not overwritten. It is important to place an evaluation statement inside a recursive function that causes the function to finish and return to the main code. Care should be taken to avoid creating an endlessly looping recursive function. The two examples below contains an "IF...THEN" evaluation that, when met, causes the function to stop calling itself and return control to the main program.
Here is an example of a subroutine which counts down from a number.
'countdown
print "Let's count down from three."
call countDown 3
end
sub countDown number
print number
if number > 1 then call countDown number-1
end sub
Now here's an example of a recursive function that returns the factorial of a number. A factorial is obtained by taking a number and multiplying it in turn by each integer less than itself. The factorial of 5 is 5x4x3x2x1=120. The factorial of 7 is 7x6x5x4x3x2x1=5040. The numbers get big in a hurry after this. For example, the factorial of 15 is 1307674368000!!
'factorial
input "Compute factorial for?"; n
print factorial(n)
end
function factorial(a)
factorial = 1
if a > 1 then factorial = a*factorial(a-1)
end function
Copyright (C) 2003 Shoptalk Systems
Liberty BASIC - http://www.libertybasic.com/