Recursion is simply any method, function, or subroutine that makes a call back to itself. Basically it would look something like this...
Void Main()
{
Main();
}
As you can see this would end up in an infinite loop which is not something we typically would want to have happen. In order to better grasp recursion let us look at the simple task of copying a directory structure.
In a directory structure there are only 2 things, files and other directories. When we copy a directory we know 2 things the location we intend to copy and the destination we want to copy to. Our header would thus look something like.
Void CopyDirectoryStructure(string RootDir, string TargetDir)
Now if we simply looped through all the directories and files in the RootDir and copied them to the target dir we would not copy any additional files in the subdirectories. Thus this is where recursion comes into play. Instead of writing some complicated decision structure to walk through all the sub dirs and determine what needs to happen we can instead simply call ourselves.
Void CopyDirectoryStructure(string RootDir, string TargetDir)
{
foreach(string file in RootDir.GetFiles())
{
//Copy File From RootDir to TargetDir
}
foreach(string dir in RootDir.GetDirs())
{
//Create new dir in target dir
//CopyDirectoryStructure(RootDir + Dir, TargetDir+Dir)
}
}
That is the basics of a recursive function. Also please note I am using psuedo code there. This will not compile and work! This method will terminate after all directories have been walked through and copied.
No comments:
Post a Comment