Java递归

本文概要

  • Java的递归例1:无限次
  • Java递归实施例2:有限次
  • Java的递归例3:阶乘数
  • Java的递归例4:斐波纳契数列
递归在java中是一个过程,其中一个方法调用自身不断。在java中调用自身的方法称为递归方法。
它使代码紧凑,但复杂的理解。
句法:
returntype methodname(){ //code to be executed methodname(); //calling same method }

Java的递归例1:无限次
public class RecursionExample1 { static void p(){ System.out.println("hello"); p(); }public static void main(String[] args) { p(); } }

输出:
hello hello ... java.lang.StackOverflowError

Java递归实施例2:有限次
public class RecursionExample2 { static int count=0; static void p(){ count++; if(count< =5){ System.out.println("hello "+count); p(); } } public static void main(String[] args) { p(); } }

输出:
hello 1 hello 2 hello 3 hello 4 hello 5

Java的递归例3:阶乘数
public class RecursionExample3 { static int factorial(int n){ if (n == 1) return 1; else return(n * factorial(n-1)); }public static void main(String[] args) { System.out.println("Factorial of 5 is: "+factorial(5)); } }

输出:
Factorial of 5 is: 120

上述程序的工作:
factorial(5) factorial(4) factorial(3) factorial(2) factorial(1) return 1 return 2*1 = 2 return 3*2 = 6 return 4*6 = 24 return 5*24 = 120

Java的递归例4:斐波纳契数列
public class RecursionExample4 { static int n1=0,n2=1,n3=0; static void printFibo(int count){ if(count>0){ n3 = n1 + n2; n1 = n2; n2 = n3; System.out.print(" "+n3); printFibo(count-1); } }public static void main(String[] args) { int count=15; System.out.print(n1+" "+n2); //printing 0 and 1 printFibo(count-2); //n-2 because 2 numbers are already printed } }

【Java递归】输出:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

    推荐阅读