English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

تعليمات Java الأساسية

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

معالجة الاستثناءات Java

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

الاستدعاء الذاتي Java

In this tutorial, you will learn about Java recursive functions and their advantages and disadvantages.

In Java, calling itselfMethodIt is called a recursive method. And, this process is called recursion.

An example in the physical world is placing two facing parallel mirrors. Any object between them will be recursively reflected.

How does recursion work?

Java recursion workflow diagram

In the above example, we called the recurse() method from inside the main method. (Normal method call). And, inside the recurse() method, we call the same recurse method again. This is a recursive call.

To stop the recursive call, we need to provide some conditions inside the method. Otherwise, the method will be called infinitely.

Therefore, we useif ... else statement(or similar method) Terminate the recursive call inside the method.

Example: factorial using recursion

class Factorial {
    static int factorial(int n) {
        if (n != 0) // termination condition
            return n * factorial(n-1); // recursive call
        else
            return 1;
    }
    public static void main(String[] args) {
        int number = 4, result;
        result = factorial(number);
        System.out.println(number + " factorial = " + result);
    }
}

output:

4 factorial = 24

في المثال السابق، لدينا طريقة تُدعى factorial(). يتم دعوة factorial() من طريقة main(). يتم استخدام متغير العدد المرسل كمعامل.

في هذا السياق، يرجى ملاحظة الجمل التالية:

return n * factorial(n-1);

طريقة factorial() تُدعى نفسها. في البداية، قيمة n في factorial() هي 4. في الاعادة التكرار التالية، يتم نقل 3 إلى طريقة factorial(). هذا العمل يستمر حتى يكون n يساوي 0.

عندما يكون n يساوي 0، يعود جملة if بـ false، لذا يعود 1. في النهاية، يتم نقل النتيجة المتراكمة إلى طريقة main().

عملية برنامج اعادة التكرار

الشكل التالي سيجعلك تدرك كيفية استخدام الاعادة التكرار في برامج اعادة التكرار بشكل أفضل.

برنامج اعادة التكرار باستخدام الاعادة التكرار

مزايا وعيوب الاعادة التكرار

عند إجراء مكالمة اعادة التكرار، سيتم تخصيص موقع جديد للاحتواء على المتغيرات على الحجم. مع كل عودة لمكالمة الاعادة التكرار، سيتم حذف المتغيرات القديمة والمعلمات من الحجم. لذلك، عادة ما يستخدم الاعادة التكرار الكثير من الذاكرة، وغالبًا ما يكون بطيئًا.

من ناحية أخرى، حلول الاعادة التكرار بسيطة بشكل كبير، وتستغرق وقتًا أقل لكتابة، تصحيح وتحسين.