Java beginners (17) Recursion

Source: Internet
Author: User

My website shares decoration Cases

To put it bluntly, you can call yourself until the method body does not conform to the conditions.

All the methods you have seen so far can call other methods. However, a method can also call itself. We call this call as a recursion. Obviously. You must include some logical judgments in the recursive method so that you can stop calling itself at the end. We will use a simple example to introduce its implementation process. We can write a method to calculate the integer power of a variable, that is, to calculate the Npower of x or x *... * X, that is, x is multiplied by its own n times. We can apply this formula to obtain the result, that is, the Npower of x is equal to the (n-1) Power of x multiplied by x.



Here is a complete program containing the recursive method power:


Public class PowerCalc
{
Public static void main (string [] arga)
{
Double x = 5.0
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)
{
It (n> 1)
Return x * power (x, n = 1); // Recersive call
Else if (n <0)
Return 1.0/power (x, n); // Negative Dower of x
Else
Return n = 0? 1.0: x; // when n is return 1. otherwise x
}
}
The output result of this program is:
5.0 to the power 4 is 625.0
7.5 to the power 5 is 23730.46875
7.5 to the power 0is 1.0
10 to the power-2 is 0.01

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.