« first day (280 days earlier)      last day (2641 days later) » 

9:35 PM
hey guys, is anyone online?
 
9:49 PM
hey guys
class FactorialExample2{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int i,fact=1;
int number=4;//It is the number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}
This is a simple factorial program using recursion
I just want to know, what is "return 1" actually doing here?
Thanks in advance
 
@ArunRaaj It returns 1...? What do you think should be there instead?
 
ya it returns 1
so logically it will be
4*3*2*1*1?
 
@ArunRaaj Yes, because 0! is 1
 
so how does the function calling chain ends up here?
it must go on
isnt it?
 
Write down factorial(4) on a piece of paper and manually follow the program
 
9:56 PM
i did it bro
 
Then you must have terminated the function call at some point
 
ya
that's what im asking
why is it being terminated after 1*1
 
because it doesn't recurse - why would it continue? it doesn't call itself in "return 0"
 
so when a functions stops being called?
 
int get_a_number() { return 5; }
what do you expect happens when this function gets called?
 
10:04 PM
ya it will return 5 only once
but what if it is case of recursion?
 
ok, so now consider:

int get_a_number(int x) {
if (x == 7) { return 2; } else { return x;}
}
what is the behavior of get_a_number(7), get_a_number(4) and get_a_number(0)
 
get_a_number(7)= returns 2
get_a_number(4) = returns 4 itself
get_a_number(0) = returns 0
m i right?
 
exactly. so now consider:

int get_a_number(int x) {
if (x == 0) { return 0; } else { return x + get_a_number(x - 1); }
}
try evaluating get_a_number(0), and get_a_number(1), and get_a_number(2)
 
get_a_number(0) = returns 0;
get_a_number(0)= returns 1+ 0 means 1
get_a_number(2)= returns 2 + 1 + 0 means 3
right?
 
10:19 PM
i assume on your second line you meant get_a_number(1), but yup that is all correct
 
ya right
thanks bro
 
you see how eventually you reached the if (x == 0) part and then stopped calling the function again, that's called the "base case"
same thing in the factorial example, you keep multiplying by one less number until you reach 0, then its just 1 by definition
some example will write it if (n == 0 || n == 1) { return 1; } just to take away a pointless multiplication by 1, but eh
 
11:02 PM
hey bro

public class demo {

int get_a_number(int a)
{
System.out.println(a);
if(a==1){
return 0;
}

else
{
a=a-1;
get_a_number(a);
System.out.println(a);
return 99;
}
}
public static void main(String[] args) {

demo d=new demo();
int result= d.get_a_number(3);
System.out.println(result);
}

}
This is a recursion program!!
The output is=
3
2
1
1
2
99
im confused about the last 3 outputs
1
2
99
How is it happening?
Help plz!!
 
11:57 PM
i got the answer
thanks
 

« first day (280 days earlier)      last day (2641 days later) »