I am learning Java using the book Java: The Complete Reference. Currently I am working on the topic Recursion.
Please Note: There are similar questi
Your confusion, I believe, comes from the fact that you think there is only one result
variable, whereas actually there is a result
variable for each function call. Therefor, old results aren't replaced, but returned.
TO ELABORATE:
int fact(int n)
{
int result;
if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
Assume a call to fact(2)
:
int result;
if ( n == 1 ) // false, go to next statement
result = fact(1) * 2; // calls fact(1):
|
|fact(1)
| int result; //different variable
| if ( n == 1 ) // true
| return 1; // this will return 1, i.e. call to fact(1) is 1
result = 1 * 2; // because fact(1) = 1
return 2;
Hope it's clearer now.
result
is a local variable of the fact
method. So each time the fact method is called, the result is stored in a different variable than the previous fact invocation.
So when fact is invoked with 3 as argument, you can imagine that its result is
result3 = fact(2) * 3
result3 = result2 * 3
result3 = 1 * 2 * 3
What happens is that the recursive call itself results in further recursive behaviour. If you were to write it out you get:
fact(4)
fact(3) * 4;
(fact(2) * 3) * 4;
((fact(1) * 2) * 3) * 4;
((1 * 2) * 3) * 4;
public class Factorial {
public static void main(String[] args) {
int n = 7;
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
System.out.println("The factorial of 7 is " + result);
}
}
A recursive solution using ternary operators.
public static int fac(int n) {
return (n < 1) ? 1 : n*fac(n-1);
}
The correct one is :
int factorial(int n)
{
if(n==0||n==1)
return 1;
else
return n*factorial(n-1);
}
This would return 1 for factorial 0. Do it believe me . I have learned this the hard way. Just for not keeping the condition for 0 could not clear an interview.