Home Theory Recursion and Memory (Vizualization)

Recursion and Memory (Vizualization)

by nikoo28
2 comments 2 minutes read

Each recursive call makes a new copy of that method (more specifically speaking ‘the variables’) in memory. Once a method ends (i.e returns some data), the copy of that returning method is removed from the memory. The recursive solutions look simple but visualization and tracing takes time. For better understanding, let us see the following example.

int Print(int n) //print numbers 1 to n backwards
    if(n == 0)
        return 0;
        return Print(n-1); //recursive call to itself again

For this example. if we call the print function with n = 4, visually our memory assignment may look like this:-

Recursion and Memory

Now, let us consider our factorial function.

//calculates the factorial of a positive integer
int Fact(int n)
    //base case: factorial of 0 or 1 is 1
    if(n == 1)
        return 1;
    else if(n == 0)
        return 1;
    //recursive case: multiply n by (n-1) factorial
        return n*Fact(n-1);

The visualization of this will be:-

factorial Visualization

You may also like


Shantun Rubal January 22, 2015 - 16:51

spelling mistake at “set’ us see the following example” line ,not something relevant to coding but still .. :P

nikoo28 January 24, 2015 - 01:06

Thanks Shantun,
The typo has been corrected.

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More