Difference between recursion and iteration



In recursive approach the function calls itself until the condition is met. And it is slower than iteration, which means it uses more memory than. Recursion is like a selection structure, and which makes code smaller and clean. And a function partially defined by itself.

In Java, C, and Python, recursion is fairly expensive compared to iteration (in general) because it requires the allocation of a new stack frame. I know that in some Scheme implementations, recursion will generally be faster than looping. In short, the answer depends on the code and the implementation

In iterative approach function is one that loops to repeat some part of the code. Using a simple for loop to display the numbers from one to ten is an iterative process.

Program using iteration:

class Factorial
{
      public static void main(String args[])
          {
              int i,fact=1,n=10;
              for(i=1;i<=n;i++)
                {
                     fact=fact*i;
                }
             System.out.println("Factorial of "+ n + " is: "+fact);
          }

}


Program using recursion:

class Factorial
{
     int fact(int n)
        {
           int result;

           if(n == 1)
               return 1;
           result = fact(n-1) * n;
               return result;
        }

     public static void main(String args[])
        { 
            Factorial f= new Factorial();
            int r = f.fact(5);
            System.out.println("Factorial of number is: " +r);
        }
}
            


Comments

Popular posts from this blog