21.08.2013 Views

OpenOffice.org BASIC Guide.pdf - OpenOffice.org wiki

OpenOffice.org BASIC Guide.pdf - OpenOffice.org wiki

OpenOffice.org BASIC Guide.pdf - OpenOffice.org wiki

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Procedures and Functions 36<br />

Recursion<br />

A recursive procedure or function is one that has the ability to call itself until it detects that<br />

some base condition has been satisfied. When the function is called with the base condition,<br />

a result is returned.<br />

The following example uses a recursive function to calculate the factorial of the numbers<br />

42, -42, and 3.14:<br />

Sub Main<br />

Msgbox CalculateFactorial( 42 ) ' Displays 1,40500611775288E+51<br />

Msgbox CalculateFactorial( -42 ) ' Displays "Invalid number for<br />

factorial!"<br />

Msgbox CalculateFactorial( 3.14 ) ' Displays "Invalid number for<br />

factorial!"<br />

End Sub<br />

Function CalculateFactorial( Number )<br />

If Number < 0 Or Number Int( Number ) Then<br />

CalculateFactorial = "Invalid number for factorial!"<br />

ElseIf Number = 0 Then<br />

CalculateFactorial = 1<br />

Else<br />

' This is the recursive call:<br />

CalculateFactorial = Number * CalculateFactorial( Number - 1 )<br />

Endif<br />

End Function<br />

The example returns the factorial of the number 42 by recursively calling the<br />

CalculateFactorial function until it reaches the base condition of 0! = 1.<br />

The recursion levels are set at different levels based on the software platform. For Windows the<br />

recursion level is 5800. For Solaris and Linux, an evaluation of the stacksize is performed and the<br />

recursion level is calculated.<br />

External links<br />

[1] http:/ / en. <strong>wiki</strong>pedia. <strong>org</strong>/ <strong>wiki</strong>/ Pass_by_reference#Call_by_reference<br />

Source: http:/ / <strong>wiki</strong>. services. openoffice. <strong>org</strong>/ w/ index. php? title=Documentation/ <strong>BASIC</strong>_<br />

<strong>Guide</strong>/ Procedures_ and_ Functions&oldid=104495<br />

Principal Authors: Fpe, Ccornell, TJFrazier

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!