Site icon Study Algorithms

Recursion and Memory (Vizualization)

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;
    else
    {
        printf("%d",n);
        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:-

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
    else
        return n*Fact(n-1);
}

The visualization of this will be:-

Exit mobile version