What is Recursion?
Recursion is a method that calls itself repeatedly until it reaches a base case.
Two Important things for recursion are stacks and base condition.
I was practicing OOPS in ABAP and was wondering if recursion was possible in ABAP, and started trying out some recursive codes.
Though recursion is rarely used in programming, it is always a very interesting and complicated topic to learn.
Below is a simple recursive program
CLASS local_class1 DEFINITION.
PUBLIC SECTION.
DATA : lv_value TYPE n VALUE 7.
METHODS display.
ENDCLASS.
CLASS local_class1 IMPLEMENTATION.
METHOD display.
me->lv_value = me->lv_value - 1.
IF me->lv_value = 0. "Base Condition
EXIT.
ENDIF.
me->display( ). "Recursion
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA lo_ref TYPE REF TO local_class1.
CREATE OBJECT lo_ref.
lo_ref->display( ).Here is a simple recursion code where the method display calls itself repeatedly until the base condition is met.
The Output of this code will be numbers printed from 7 till 1.
Another Program of Fibonacci series using Recursion.
CLASS local_class1 DEFINITION.
PUBLIC SECTION.
METHODS fibonacci
IMPORTING
n TYPE i
RETURNING
VALUE(result) TYPE i.
ENDCLASS.
CLASS local_class1 IMPLEMENTATION.
METHOD fibonacci.
IF n <= 1. " Base Condition 1
result = 1.
RETURN.
ELSEIF n = 2. " Base Condition 2
result = 1.
RETURN.
ENDIF.
result = fibonacci( n - 1 ) + fibonacci( n - 2 ).
ENDMETHOD.
ENDCLASS.
PARAMETERS p_fib TYPE i.
START-OF-SELECTION.
DATA lo_ref TYPE REF TO local_class1.
DATA res TYPE i.
CREATE OBJECT lo_ref.
lo_ref->fibonacci( EXPORTING n = p_fib
RECEIVING result = res ).
WRITE : / , 'The ' , p_fib , 'th fibonacci number is ' , res.The above program gives us the nth fibonacci number as the output.
Please do share your on views on recursion in ABAP.