Back to Basics: Recursion
Sunday, October 2, 2011 at 9:30AM
Shaun Hess in Back to Basics, Powershell, Powershell, Programming, Programming

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:

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.

Article originally appeared on shaunhess.com (http://www.shaunhess.com/).
See website for complete article licensing information.