Alex
Alex

Reputation: 876

Recursive function calls working behind the scenes

So I can't wrap my head around recursive function calls especially with this example:

int Addup(int n)
{
    //6
    if(n <= 1)
        return 1;
    else 
        return n + Addup(n - 1);
    /*
    6 + 5 + 4 + 3 + 2 + 1
    */
}

Now if for example we did Addup(6), how will that work, what will the program do at runtime? Will it chain all the evaluations after the n then sum them together. I really can't visualize it.

If someone could have a simple way of demonstrating what actually happens at runtime it would be really great.

Thanks in advance.

Upvotes: 0

Views: 41

Answers (1)

molbdnilo
molbdnilo

Reputation: 66459

The secret to understanding recursion is that recursive functions work exactly like non-recursive functions.

Your functions work exactly like these:

int Addup_1(int n)
{
    return 1;
}

int Addup_2(int n)
{
    if(n <= 1)
        return 1;
    else 
        return n + Addup_1(n - 1);
}

int Addup_3(int n)
{
    if(n <= 1)
        return 1;
    else 
        return n + Addup_2(n - 1);
}

int Addup_4(int n)
{
    if(n <= 1)
        return 1;
    else 
        return n + Addup_3(n - 1);
}

int Addup_5(int n)
{
    if(n <= 1)
        return 1;
    else 
        return n + Addup_4(n - 1);
}

int Addup_6(int n)
{
    if(n <= 1)
        return 1;
    else 
        return n + Addup_5(n - 1);
}

Upvotes: 3

Related Questions