Java Reference
In-Depth Information
System.out.println(x + " to the power 4 is " + power(x,4));
System.out.println("7.5 to the power 5 is " + power(7.5,5));
System.out.println("7.5 to the power 0 is " + power(7.5,0));
System.out.println("10 to the power -2 is " + power(10,-2));
}
// Raise x to the power n
static double power(double x, int n) {
if(n > 1)
return x*power(x, n-1);
// Recursive call
else if(n < 0)
return 1.0/power(x, -n);
// Negative power of x
else
return n == 0 ? 1.0 : x;
// When n is 0 return 1,
otherwise x
}
PowerCalc.java
This program produces the following output:
5.0 to the power 4 is 625.0
7.5 to the power 5 is 23730.46875
7.5 to the power 0 is 1.0
10 to the power -2 is 0.01
How It Works
The power() method has two parameters, the value x and the power n . The method performs four differ-
ent actions, depending on the value of n :
n >
1
A recursive call to power() is made with n reduced by 1, and the value that is returned is multiplied by
x . This is effectively calculating x n as x times x n — 1 .
x — n is equivalent to 1/x n so this is the expression for the return value. This involves a recursive call to
power() with the sign of n reversed.
n <
0
x 0 is defined as 1, so this is the value returned.
n =
0
x 1 is x , so x is returned.
n =
1
As a rule, you should use recursion only where there are evident advantages in the approach, as recursive
method calls have quite of lot of overhead. This particular example could be more easily programmed
as a loop, and it would execute much more efficiently. You could also use the Math.pow() method to
produce the result. One example of where recursion can be applied very effectively is in the handling of
data structures such as trees. Unfortunately these don't make convenient illustrations of how recursion
works at this stage of the learning curve because of their complexity.
Before you can dig deeper into classes, you need to take an apparent detour to understand what a package
is in Java.
Search WWH ::




Custom Search