You may remember studying Logo earlier. Logo can define functions that can be called recursively as follows:
TO WALK
FD RANDOM 20
LT RANDOM 360
SETPC ((RANDOM 100) + 1)
WALK
END
This function will continue forever, as will this:
TO SQUARE :LENGTH
FD :LENGTH RT 90
SQUARE :LENGTH
END
Where a limit is known in advance a condition can be used to stop the iteration:
TO SQUARE :LENGTH :COUNTER
FD :LENGTH RT 90
IF :COUNTER >= 4 [STOP] [SQUARE :LENGTH :COUNTER + 1]
END
The following code uses recursion to create a square spiral:
TO SQUIRAL :LENGTH
REPEAT 2 [FD :LENGTH LT 90]
SQUIRAL :LENGTH + 3
END
The following two functions together draw a Koch snowflake:
TO SIDE :LENGTH
IF :LENGTH < 2 [FD :LENGTH STOP]
SIDE :LENGTH / 3 LT 60
SIDE :LENGTH / 3 RT 120
SIDE :LENGTH / 3 LT 60
SIDE :LENGTH / 3
END
TO SNOWFLAKE :LEN
SIDE :LEN RT 120
SNOWFLAKE :LEN
END
The following code implements an algorithm to draw a binary tree:
TO TREE :LEN
IF :LEN < 2 [STOP]
LT 45 FD :LEN
TREE :LEN / 2
BK :LEN RT 90
FD :LEN
TREE :LEN/2
BK :LEN LT 45
END
| Factorials | GCD | Towers of Hanoi | Quick Sort |