یه تابستون متفاوت با یه تصمیم هوشمندانه! دوره هوش مصنوعی یه تابستون متفاوت با یه تصمیم هوشمندانه! دوره هوش مصنوعی
🎯 ثبت نام

آموزش Java – توابع بازگشتی (Recursion) در Java

آموزش Java – توابع بازگشتی (Recursion) در Java

Recursion یا الگوریتم بازگشتی زمانی اتفاق می افتد که یک متد خود را به کرات صدا بزند. به متدی که خود را فراخوانی می کند، در اصطلاح تابع recursive یا بازگشتی گویند.

این الگوریتم اگرچه سبب کوتاه تر (فشرده تر) شدن کد می شود، با این وجود به پیچیدگی آن نیز افزوده و خوانایی و فهم آن را دشوارتر می نماید.

دستور تعریف و استفاده از یک تابع بازگشتی در جاوا به شرح زیر می باشد:

1
2
3
4
5
returntype methodname(){ 
//code to be executed 
methodname();//calling same method 
}
<button></button>

پیاده سازی تابع بازگشتی مثال 1: فراخوانی بی نهایت

1
2
3
4
5
6
7
8
9
10
public class RecursionExample1 { 
static void p(){ 
System.out.println("hello"); 
p(); 
public static void main(String[] args) { 
p(); 
<button></button>

خروجی:

hello
hello
...
java.lang.StackOverflowError

پیاده سازی تابع بازگشتی مثال 2: فراخوانی خود به دفعات محدود

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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(); 
<button></button>

خروجی:

1
2
3
4
5
6
hello 1
hello 2
hello 3
hello 4
hello 5
<button></button>

پیاده سازی تابع بازگشتی مثال 3: محاسبه ی فاکتوریل

1
2
3
4
5
6
7
8
9
10
11
12
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)); 
<button></button>

خروجی:

1
Factorial of 5 is: 120<button></button>

نحوه ی عملکرد متد فوق:

1
2
3
4
5
6
7
8
9
10
11
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
<button></button>

پیاده سازی تابع بازگشتی مثال 4: محاسبه ی سری فیبوناتچی

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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    
<button></button>

خروجی:

1
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377<button></button>
1396/07/21 9505 3072
رمز عبور : tahlildadeh.com یا www.tahlildadeh.com
نظرات شما

نظرات خود را ثبت کنید...