Page 407 - Computer science 868 Class 12
P. 407

11.2 TYPES OF RECURSION
                 Recursion is broadly classified into two types:

                 1.  Direct recursion
                 2.  Indirect recursion

                 11.2.1 Direct Recursion
                 Direct recursion is the normal recursive technique where a function calls itself from its own body. This is the most
                 common form of recursive technique.
                 It can be demonstrated as follows:
                    <return type> function1(parameter)
                    {
                        if <base case>
                            <body if true>
                        else
                            function1(parameter)
                    }
                 Let us demonstrate direct recursion by printing ‘n’ natural numbers using the recursive method void print(int n).
                    class Natural
                    {
                        void print(int n)
                        {
                            if(n>10)   // base case
                            {
                                System.out.println();
                            }
                            else
                            {
                                System.out.println(n);
                                print(n+1);   // recursive case
                            }
                        }
                        public static void main()   // main method
                        {
                            Natural ob = new Natural();
                            ob.print(1);   // method calling
                        }
                    }
                 11.2.2 Indirect Recursion
                 Indirect recursion is a coding technique where the first method calls the second method which in turn calls the first
                 method in a circular fashion.
                 It can be demonstrated as:

                    <return type>  function1( parameter)
                    {
                       if <base case>
                         <body if true>
                      else
                         function2(parameter)
                    }
                    <return type>  function2( parameter)
                    {
                       if <base case>
                         <body if true>

                                                                                                                       405
                                                                                                           Recursion   405
   402   403   404   405   406   407   408   409   410   411   412