Thursday 22 February 2018

Recursion Vs Iteration



Recursion vs. Iteration


In simple words ‘recursion’ or ‘iteration’ means to repeat around until you find a stopping condition. So it’s obvious that if we don’t find any stopping condition then it will ultimately fall into an infinite loop. Both recursion and iteration are equivalent in power and hence inter-changeable or inter-convertible. That means for every recursive program there is an iterative approach & vice-versa.


Example Problem: Write a program to print ‘hello’ 3 times.


Recursive Approach:


void fun( int n){

if(fun==0) return;
else {
      printf(“hello”);
      fun(--n);
     }
}
int main(){
fun(3);
return 0;
}


Iterative Approach:


int main(){
int i=0;
while(i<3){
           printf(“hello”);
           i++;
          }
return 0;
}





You can also simply write ‘printf(“hello”); ’ 3 times inside main function (manual approach). You might think that why to use recursion or iteration then. Now if you are asked to print ‘hello’ 1000 times then…??? You can imagine now which approach would be better.


Important point to note:


  1. Recursion, iteration & manual approach are equivalent in terms of power. You can write any program using any one of the approach and also convert them into other approaches without changing the meaning of the program.
  2. All the recursive programs require an additional stack data structure for their execution.
  3. Iterative programs may require additional storage space as per the convenience of the programmer.

No comments:

Post a Comment