WD: Creating Recursive Functions Using WordBasic

ID: Q72280

The information in this article applies to:

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, "Microsoft Quick C Programming" (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 "Find Factorial Of: ", 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 "Find Factorial Of: ", 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 "a" by
      Factorial = result                 'factorial of a-1
   End Function

Both methods return the same result; however, the recursive method is slightly more efficient.

REFERENCES

The Waite Group's book "Microsoft Quick C Programming," pages 164-167

Additional query words:

Keywords          : kbmacro wordnt kbmacroexample winword ntword macword word6 winword2 word7 word95 
Version           : WINDOWS:1.0,1.1,1.1a,2.0,2.0a,2.0a- CD,2.0b,2.0c,6.0,6.0a,6.0c,7.0,7.0a; MACINTOSH:6.0,6.0.1,6.0.1a
Platform          : MACINTOSH Win95 WINDOWS winnt
Issue type        : kbhowto

Last Reviewed: February 4, 1998