xxxxxxxxxx
package com.company.Recursion;
import java.util.Scanner;
public class ExRecursion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int value = input.nextInt();
foo(value);
}
public static int foo(int n){
if (n<=1){
return 1;
} else {
return foo(n-1) + foo(n-2);
}
}
}
xxxxxxxxxx
The idea of recursion is that instead of conquering the problem top to bottom
for graph/tree or start to end for array/string in normal for/while loops,
in recursion you conquer the problem from bottom to top or end to start.
What's before the recursive call(s) gets executed going top to bottom
or start to end and what's after the recursive call(s) gets executed
going bottom to top or end to start.
xxxxxxxxxx
When a method in any programming language calls itself for a smaller task,
then it is called as recursion and the method is called as recursive method
Recursion follows devide and conqure technique in which a problem is solved
by breaking it into a smaller problem
Whenever a recursion is not handled with a proper base condition, it gives a
stack overflow error
A base condition is a condition in recursive calls that is used to return a
recursive call and it makes recursion possible in programming
EXAMPLE JAVA CODE:
public static long factorial(int n){
if (n == 1)
return 1;
else
return n * factorial(n-1);
}
xxxxxxxxxx
// Basic Recursive function
// It works in all languages but lets try with C
// lets make a greedy strlen
int my_recursive_strlen(int index, char *str) // note that index must be set at 0 to work in this case
{
if (str[index] == '\0')
return index + 1;
else
return my_recursive_strlen(index++); // i send index + 1 to next function call
// this increment index in our recursive stack
}
void main(void)
{
printf("length of Bonjour = %d\n", my_recursive_strlen(0, "bonjour"));
}
//output : length of Bonjour = 7
// Recursive functions are greedy and should be used in only special cases who need it
// or who can handle it.
// a function become recursive if she calls herself in stack
xxxxxxxxxx
package com.company.Recursion;
import java.util.Scanner;
public class ExRecursion1 {
public static void main(String[] args) {
foo(3,2);
}
public static int foo(int n, int m){
if (n<=1 || m<=1){
return 2;
} else {
return foo(n-1, m) + foo(n, m-2);
}
}
}
xxxxxxxxxx
void recurse()
{
..
recurse();
..
}
int main()
{
..
recurse();
..
}