WD: Creating Recursive Functions Using WordBasicLast reviewed: February 2, 1998Article ID: Q72280 |
The information in this article applies to:
SUMMARYIn Microsoft Word, you can write macros that use recursive functions.
MORE INFORMATIONIn 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.
REFERENCESThe Waite Group's book "Microsoft Quick C Programming," pages 164-167
|
Additional query words:
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |