Sunday
Oct022011
Back to Basics: Recursion

Google recursion and besides for the joke "Did you mean: recursion" you'll find a plethora of examples, definitions, and people showing you how clever they are.
Put simply, recursion is broken down like this:
- Base case - simpliest possible solution
- Inductive step - break problem into a simplier version of the same problem with some other steps to execute.
Ok clear as mud. So as always lets take a problem and break it down.
A lot of examples show recursion using the Fibonacci sequence. However I always liked the "Blastoff!" example from How to Think Like a Computer Scientist.
Alright lets define a function:
function countdown { param( [int]$n ) if ($n -le 0) { Write-Host "Blastoff!" } else { $n countdown($n-1) } }
Now lets source our function and run it:
PS H:\Development\Powershell> . .\recursion.ps1 PS H:\Development\Powershell> countdown -n 10 10 9 8 7 6 5 4 3 2 1 Blastoff!
See recursion isn't so bad after all.
tagged
Powershell,
Programming in
Back to Basics,
Powershell,
Programming





Reader Comments