+ 1
Recursion in java
Hey guys, I am having trouble understandin recursion in java. Can somebody explain me how it works? Please show an example ,if possible.
4 Respuestas
+ 1
Recursion is a function that call itself. The example of recursion is factorial.
public class Program
{
//Condition so this function will stop running
public static int factorial(int n){
if(n == 0 || n == 1){
return 1;
}
return n * factorial(n-1);
}
public static void main(String[] args){
System.out.println(factorial(5)); //Output 120
}
}
In the main function, we call factorial function with 5 as the argunent.
factorial(5) returns 5 and calls factorial(4) because 5 is greater than 1.
factorial(4) returns 4 and calls factorial(3) because 4 is greater than 1.
factorial(3) returns 3 and calls factorial(2) because 3 is greater than 1.
factorial(2) returns 2 and calls factorial(1) because 2 is greater than 1.
factorial(1) returns 1 because 1 equals to 1.
So, factorial(5) returns 5 * 4 * 3 * 2 * 1 = 120.
+ 1
It depends.
Recursion works better than loop because it is easier to implement.
Loop works better than recursion because it uses less memory than recursion especially against recursion that is too deep such as factorial(50).
0
so basically a recursion works better than loops?
0
ok thanks (: