Microsoft KB Archive/72280

{|
 * width="100%"|

WD: Creating Recursive Functions Using WordBasic

 * }

Q72280

-

The information in this article applies to:


 * Microsoft Word for Windows, versions 1.0, 1.1, 1.1a, 2.0, 2.0a, 2.0a-CD, 2.0b, 2.0c, 6.0, 6.0a, 6.0c
 * Microsoft Word for Windows NT, version 6.0
 * Microsoft Word for Windows, versions 7.0, 7.0a
 * Microsoft Word for the Macintosh, versions 6.0, 6.0.1, 6.0.1a

-

SUMMARY
In Microsoft Word, you can write macros that use recursive functions.

MORE INFORMATION
In WordBasic, functions can call other functions; additionally, as in many other languages, these functions can call themselves. Any function that makes a call to itself is considered recursive. For more information on recursive functions, refer to the book, &quot;Microsoft Quick C Programming&quot; (published by the Waite Group), pages 164-167.

The following two examples figure the factorial of a number. The first example does not use recursion; the second example uses recursion.

Sample Macros to Figure the Factorial of a Number (n!)

Method 1: Finding (n!) Without Recursion
  Sub MAIN Input &quot;Find Factorial Of: &quot;, a    'Allows user input result = Factorial(a)             'Only function call Print result                      'Prints the final result End Sub

Function Factorial(a) If a = 0 Then                     'If a = 0 return 1 (0!=1) sum = 1 Else                              'calculate with loop sum = a        For x = a - 1 To 1 Step - 1 sum = sum * x        Next x      End If      Factorial = sum End Function

Method 2: Finding (n!) with Recursion
  Sub MAIN Input &quot;Find Factorial Of: &quot;, a    'Allows user input result = Factorial(a) Print result End Sub

Function Factorial(a) If a = 0 Then                     '(0!=1 so return 1) result = 1 Else result = a * Factorial(a - 1)  'if not 0 then End If                            'multiply &quot;a&quot; by      Factorial = result                 'factorial of a-1 End Function Both methods return the same result; however, the recursive method is slightly more efficient.