Page 369 - computer science (868) class 11
P. 369

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
                        }
                    }
                 The output of the preceding program is as follows:
                 1
                 2
                 3
                 4
                 5
                 6
                 7
                 8
                 9
                 10
                 12.2.2 Indirect Recursion
                 Indirect recursion is a coding technique in which 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>





                                                                                                                       367
                                                                                                           Recursion   367
   364   365   366   367   368   369   370   371   372   373   374