Thinking Recursively
Recursion is the property of defining a function in terms of itself.
public class Factorial {
public static int fact(int n) {
int p = 1;
for (int i = 1; i <= n; i++) {
p *= i;
}
return p;
}
public static void main(String[] args) {
int result = fact(5);
System.out.println("Factorial: " + result);
}
}
public class Factorial {
public static int fact(int n) {
if (n == 0)
return 1;
else
return n * fact(n - 1);
}
public static void main(String[] args) {
int result = fact(5);
System.out.println("Factorial: " + result);
}
}
Each recursive function call adds a new memory zone in the stack until it reaches the base case.
public class Combinations {
public static int comb(int n, int k) {
if (n == k || k == 0)
return 1;
else
return comb(n - 1, k - 1) + comb(n - 1, k);
}
public static void main(String[] args) {
System.out.println(comb(5, 2));
}
}
Each recursive function maintains its local variables separately on the stack. A function call will continue until it reaches the base case.
public class Factorial {
public static void fact(int n, int[] r) {
if (n == 0)
r[0] = 1;
else {
fact(n - 1, r);
r[0] *= n;
}
}
public static void main(String[] args) {
int[] a = new int[1];
fact(4, a);
System.out.println(a[0]);
}
}
public class Factorial {
public static int fact(int n) {
int result;
if (n == 0)
result = 1;
else
result = fact(n - 1) * n;
return result;
}
public static void main(String[] args) {
int x = fact(3);
System.out.println("Factorial of 3: " + x);
}
}