logo

Rekurzió Java nyelven

A rekurzió a java-ban egy olyan folyamat, amelyben egy metódus folyamatosan hívja magát. A Java-ban egy olyan metódust, amely meghívja magát, rekurzív metódusnak nevezzük.

Ez kompaktsá teszi a kódot, de bonyolulttá teszi a megértést.

Szintaxis:

 returntype methodname(){ //code to be executed methodname();//calling same method } 

Java rekurziós példa 1: Végtelen idő

 public class RecursionExample1 { static void p(){ System.out.println('hello'); p(); } public static void main(String[] args) { p(); } } 

Kimenet:

 hello hello ... java.lang.StackOverflowError 

Java rekurziós példa 2: Véges idők

 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) { < pre> <p>Output:</p> <pre> hello 1 hello 2 hello 3 hello 4 hello 5 </pre> <h2>Java Recursion Example 3: Factorial Number</h2> <pre> 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(&apos;Factorial of 5 is: &apos;+factorial(5)); } } </pre> <p>Output:</p> <pre> Factorial of 5 is: 120 </pre> <p> <strong>Working of above program:</strong> </p> <pre> 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 </pre> <h2>Java Recursion Example 4: Fibonacci Series</h2> <pre> public class RecursionExample4 { static int n1=0,n2=1,n3=0; static void printFibo(int count){ if(count&gt;0){ n3 = n1 + n2; n1 = n2; n2 = n3; System.out.print(&apos; &apos;+n3); printFibo(count-1); } } public static void main(String[] args) { int count=15; System.out.print(n1+&apos; &apos;+n2);//printing 0 and 1 printFibo(count-2);//n-2 because 2 numbers are already printed } } </pre> <p>Output:</p> <pre> 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 </pre></=5){>

Java rekurziós példa 3: Tényezőszám

 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(&apos;Factorial of 5 is: &apos;+factorial(5)); } } 

Kimenet:

 Factorial of 5 is: 120 

A fenti program működése:

 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 rekurziós példa 4: Fibonacci sorozat

 public class RecursionExample4 { static int n1=0,n2=1,n3=0; static void printFibo(int count){ if(count&gt;0){ n3 = n1 + n2; n1 = n2; n2 = n3; System.out.print(&apos; &apos;+n3); printFibo(count-1); } } public static void main(String[] args) { int count=15; System.out.print(n1+&apos; &apos;+n2);//printing 0 and 1 printFibo(count-2);//n-2 because 2 numbers are already printed } } 

Kimenet:

 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377