I'm just learning about recursion in my C++ book and man is it ever confusing, is it going to be 100% necessary for me to master this before moving on? I don't ever really see it in too many programs I've dinked around in so I'm guessing it's not used very often but I could be wrong. Took me about 15 minutes (and a little bit of cheating) just to write this simple recursion program...
I hate recursion when it doesn't work, it's hard to follow linearly.
I love it when it works though, it make thing look so simple!
Try using it for applications where it makes sense to use it. For instance, a directory structure (file system) has a tree structure. You have root directory(s) (on Windows "C:", on Unix "/", …, etc) and they have folders, and each folder has folders, and so on. So in pseudo-code:
1 2 3 4 5 6 7 8 9 10
//print all the files in this root directory, as well as all files in all of its folders
voidprintAllFiles(rootDir) {
filesAndFolders[] = rootDir.getAllFilesAndFolders();
foreach( filesAndFolders as fileOrFolder )
if( fileOrFolder is FILE )
print( fileOrFolder ); //print the file
elseif( fileOrFolder is FOLDER )
printAllFiles( fileOrFolder ); //pass folder to another call to this function
// so it prints all of it's files and folders too
}
is it going to be 100% necessary for me to master this before moving on?
No. I don't know why it's taught to beginners, it really shouldn't be.
I don't ever really see it in too many programs I've dinked around in so I'm guessing it's not used very often but I could be wrong
You're not wrong.
Practical uses for recursion are few and far between. About the only thing off hand I can think of where uses are warranted is something like navigating a tree or a flood fill algorithm.
As one of my math teachers said, obviously any recursive algorithm can be converted to a non-recursive one (because that is exactly what your C++ compiler does).
So, recursion is not conceptually different from a while cycle and some pushing and popping of variables to and from a stack ;)
Im also learning recursion. You might know more than me right now but if you think of it as a mirror refelcting a mirror it keeps going till the small angel (n) causes the mirrors to go to the side and stop. So its calling itself and once it finishes it prints from the inner most first out.