views:

330

answers:

3

say there is a function to calculate factorial(n)

Does factorial(7) creates 7 function object for each of n from 1 to 7

and use those values when ever necessary (for factorial(8) as like factorial(7)*8)

+1  A: 
Charlie Martin
+3  A: 

It depends, sounds like you are talking about a recursive factorial function:

int factorial(int n) {
    return n>=1 ? n * factorial(n-1) : 1;
}

This function will invoke itself recursively the number of times needed to calculate the given factorial(n).

Mostly all recursive functions can be transformed into an iterative solution by using a stack to accumulate the consecutive results...

int factorial(int n) {
    int accu = 1;
    int i;
    for(i = 1; i <= n; i++) {
        accu *= i;
    }
    return accu;
}
CMS
+1 for mentioning the iterative approach - I think too many people are in love with recursion. However, I do not understand your use of "stack"; per the variable's name, you're just using an accumulator.
PTBNL
+5  A: 

It depends on the language and the language implementation.

In many functional languages (e.g. Haskell), a function is guaranteed to change nothing; only to return a value. This lack of side effects allows the language to remember/cache, or "memoize", the results of function calls.

In a less sophisticated language, 7 distinct function call frames might be placed on the stack and popped off.

A properly written factorial function in many functional languages would also be tail recursive; in that case the language might choose to simply jump from the bottom of the function to the top to avoid creating another function call. In this case the language is turning the recursive function into a loop "for free".

Joe Koberg