Recursion in Java factorial program -
what know recursion is function calls itself , has base of operations status stops. professor wrote programme , called recursion occurring in , said no, it's not. confused it. asking clear confusion. programme made him below in code:
int fact(int n) { if (n == 0) { homecoming 1; } (int = n; >= 1; i--) { s1.push(i); } homecoming return_result(); } int return_result() { int f = 1; while (s1.top != -1) { f = f * s1.pop(); } homecoming f; }
first want explain facts:
factorial computed next formula :n! = n * n-1 * n-2 * n-3 * .....* 3 * 2 * 1
stack works in lifo = lastly in first out
or filo = first in lastly out
so code next first puts numbers n 1 in stack pops each 1 , multiply current result factorial @ end
and way iterative version factorial (non-recursive), recursive version following
int fact(int n) { int result; if(n==1) homecoming 1; result = fact(n-1) * n; homecoming result; }
java recursion
No comments:
Post a Comment