public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
public static void main(String[] args) {
int n = 5;
int result = factorial(n);
System.out.println("Factorial of " + n + " is " + result);
}
What is “Factorial of 5 is 120”
refers to the fact that the same computation recurs, or occurs repeatedly, as the problem is solved.
What is recursion?
ArrayList<type> nameofarraylist= new ArrayList<type>();
What is “creating an ArrayList”?
public static double power(double x, int n) {
if (n == 0) {
return 1;
} else if (n % 2 == 0) {
double half = power(x, n/2);
return half * half;
} else {
double half = power(x, (n-1)/2);
return half * half * x;
}
}
public static void main(String[] args) {
double x = 2.0;
int n = 5;
double result = power(x, n);
System.out.println(x + " to the power of " + n + " is " + result);
}
What is “2.0 to the power of 5 is 32.0”
We first find out whether the value is in the first or second half of the array. The last value in the first half of the data set, a[4], is 9, which is smaller than the value we are looking for. Hence, we should look in the second half of the array for a match, that is, in the sequence.
What is binary search?
Method used to get the size of an ArrayList
What is Size()?