Using recursions cautiously
Recursions are a form of programming design in which the function calls itself multiple times to solve a problem by breaking down a large solutions set into multiple small solution sets. The code size definitely shortens. However, if not used properly, recursions can fill up the call stack really fast and you can run out of memory.
Getting ready
To get started with this recipe, you should have some prior knowledge of call stacks and how memory is assigned during a function call. You need a Windows machine with a working copy of Visual Studio.
How to do it…
In this recipe, you will see how easy it is to use recursions. Recursions are very smart to code but also can lead to some serious problems:
- Open Visual Studio.
- Create a new C++ project.
- Select Win32 Console Application.
- Add a source file called
main.cpp
or anything that you want to name the source file. - Add the following lines of code:
#include <iostream> #include <conio.h> using namespace std; int RecursiveFactorial(int number); int Factorial(int number); int main() { long iNumber; cout << "Enter the number whose factorial you want to find"; cin >> iNumber; cout << RecursiveFactorial(iNumber) << endl; cout << Factorial(iNumber); _getch(); return 0; } int Factorial(int number) { int iCounter = 1; if (number < 2) { return 1; } else { while (number>0) { iCounter = iCounter*number; number -= 1; } } return iCounter; } int RecursiveFactorial(int number) { if (number < 2) { return 1; } else { while (number>0) { return number*Factorial(number - 1); } } }
How it works…
As you can see from the preceding code, both the functions find the factorial of a number. However, when using recursion, the stack size will grow immensely with each function call; the stack pointer has to be updated every call and data pushed onto the stack. With recursion, as the function calls itself, every time a function is called from within itself the stack size will keep on rising until it runs out of memory and creates a deadlock or crashes.
Imagine finding the factorial of 1000. The function will be called within itself a very large number of times. This is a recipe for certain disaster and we should avoid such coding practices to a great extent.
There's more…
You can use a larger datatype than int if you are finding the factorial of a number greater than 15, as the resulting factorial will be too large to be stored in int.