Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Recursion be named as a simple function call?

Please consider an Recursive function :

 1)   int calc(int num)
       {

 2)    sum=sum+num;//sum is a global variable

 3)    num--;

 4)    if(num==0)
 5)    return sum;

 6)    calc(num);

       }

It calculates the sum of an integer . My teacher told me it's not recursion, but a simple function call, because you need to pass num-- as an argument and return calc(num--) .

I was shocked, as I knew only one thing when a function call itself, its recursion.

She also gave the reason, that line no. 2 and 3 is stored extra in stack memory. I have no idea what she was referring to.So after going through stack storage thingy:

enter image description here

Here, I noticed that the function arguments passed are in a recursive way, like n-- in my function. So that they can be linked to the next function call.

For just this sake, can we term it a simple function call instead of recursion?

like image 497
joey rohan Avatar asked Mar 22 '23 17:03

joey rohan


1 Answers

The teacher has something quite specific in mind even though what you presented is, technically, recursive. Another form which wouldn't depend upon the global would look something like this:

int calc(int num)  // Assume this is valid for non-negative numbers
                   // In that case, type "unsigned int" would be more appropriate
{
    if ( num < 0 )
        return -1;  // Consider this an error; won't happen in recursive case

    if ( num == 0 )
        return 0;

    return num + calc(num-1);
}
like image 125
lurker Avatar answered Mar 27 '23 14:03

lurker