is there’s a direct relationship between recursive functions and the memory stack, for more explanation consider that code:
public static int triangle(int n) {
System.out.println(“Entering: n = ” + n);
if (n == 1) {
System.out.println(“Returning 1”);
return 1;
} else {
int temp = n + triangle(n - 1);
System.out.println(“Returning“ + temp);
return temp;
}
}
in this example where will the values 2,3,4,5 be stored until the function returns ? note that they will be returned in LIFO(LastInFirstOut) is these a special case of recursion that deals with the memory stack or they always goes together?
Yes, there is direct relationship between recursion functions and memory stack as some function with a high limit will crash your program just because stack size limit is reached and function will override parts of your program code (that is what we call stack-overflow).
R: Recursive
I: Iterative
I hope this makes sense, for iterative call function will be pushed to the stack once done it goes off from the stack and the next call will load a similar function, in the other hand the recursive function loads into the stack and calls itself and reloads the stack with each call, and then they start to go off (LIFO last one called first one out) when the stopping condition is reached.
So now to be specific to your matter, the n value as you said will be hold in the memory when stopping condition is met then the last function will display n, and then exits to give the hand to the function that just called it which will also display its own value of n and the same thing will be repeated until the very first function called, however the iterative function will display a value of a counter n (only one variable used and we are changing its value).
The below is a good article about stackoverflow,
http://en.wikipedia.org/wiki/Stack_overflow