Page 408 - Computer science 868 Class 12
P. 408

else
                       function1(parameter)
                  }
              Let us demonstrate indirect recursion by printing ‘n’ natural numbers using recursive methods void odd(int n) and
              void even(int a)
                  class Natural
                  {
                    void odd(int n)
                    {
                      if(n>10)  // base case
                      { System.out.println();}
                      else
                      { System.out.println(n); // printing odd numbers
                       even(n+1);   // calling method even()
                      }
                    }
                    void even(int a)
                    {
                      if(a>10)  // base case
                      { System.out.println();}
                      else
                      { System.out.println(a);  // printing even numbers
                       odd(a+1);  // calling method odd()
                      }
                    }
                    public static void main()  // main
                    {
                     Natural ob=new Natural();
                     ob.odd(1);
                    }
                  }
              Advantages of Recursion
              Some of the advantages of recursion are as follows:
              •  Recursion is used extensively in backtracking algorithms. The backtracking algorithm is a problem-solving algorithm
                 that involves building a set of all the solutions incrementally. And the solutions that don’t satisfy the conditions are
                 removed during the course of program execution. It uses a brute force approach while trying to find a solution to the
                 problem. Example:  solving Sudoku, solving crosswords, etc.
              •  Recursion adds clarity and (sometimes) minimises the time taken to write and debug a code.
              •  Certain algorithms like Tree Traversal, and Tower of Hanoi can be solved easily using recursion as compared to iteration.
              •  Recursion decreases time complexity.

              Disadvantages of Recursion
              Some of the disadvantages of recursion are as follows:
              •  It consumes a lot of memory. As the method calls itself repeatedly, every time the variable is allocated with a new
                 memory on the stack.
              •  Because of its memory stack manipulation, recursion is a slow process.
              •  For a beginner, it is difficult to understand the concept of recursion.

              Recursion vs Iteration
              From the coding process, we can see that any iterative structure can be represented by recursive methods. Let us see
              the difference between looping and recursion.


                406406  Touchpad Computer Science-XII
   403   404   405   406   407   408   409   410   411   412   413