#Recursion in Modula 2
8 messages in this thread
Larry, here is a cute and useful example of recursion:
..
. PROCEDURE WriteOctal (n : INTEGER);
. BEGIN
. IF n <= 7 THEN
. WriteInt (n,1)
. ELSE
. WriteOctal (n DIV 8);
. WriteInt (n MOD 8, 1)
. END
. END WriteOctal;
. This should be as easy as Factorial, but not as obviously converted to
iteration.
…..Richie "To iterate is human, to recurse divine!"
Richie, nice one! And definitely useful for those poor souls who've lost their
thumbs and need octal.
Regards, Larry.
Richard,
Doesn't work with negative numbers.
True, but negative numbers can be taken care of before calling
WriteOctal…..Richie
Richard,
Other than that, it's a great example.
Negative numbers on a computer are nothing but an illusion: Everything is
really a cardinal!! Besides why would you want to print the Octal
representation of a negative number??
(And who the hell needs Octal anyway, Richie?? Long Live Hex! :-))
Granted, using the Factorial example to demonstrate recursion is very silly.
And I think that Wirth agrees that for Factorials, iteration is preferred.
A better example would be something like the Towers of Hanoi or the
Knight's Tour problems. See if you can code these using iteration. Then do it
using recursion. All of a sudden you'll see the beauty of recursion. As they
say:
'To Iterate is Human; To Recurse – Divine'