Di Posting Oleh : Simple Learning
Kategori : difference between recursion and iteration example iteration Recursion
Major difference and similarities between recursion and iteration
- Both works repeatedly, iteration uses loops and recursion uses functions call
- Both have termination cases one has a relation expression in loop and one has a base case in if conditoin
- Iteration checks repeatedly its relational expression and recursion checks repeatedly its base case
- Iteration control by counter variable and recursion by its base case
- Both can be run infinitely when loops condition never false and base case if condition never becomes true
Memory differences
In case of recursion every calls put on stack and save into memory the more calls more memory consumption. In worst case if base case never becomes true or programmer has forget to write base case it will cause stack over flow and at some point you will see calls has stopped. In case of loop it will run infinitely and never stops.
Which one to choose?
It depends on the requirement both are not superior to each other in every scenario both have their own benefits and draw backs in different conditions.
For example if you want to write the Fibonacci series program in c++ using loop then it may
- hard to write
- less overhead to memory
- less readable
If you use recursion function code
long fib(long n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
- More readable
- High memory consumption
- Easy to write if you have the good concept of recursion
0 Response to "Difference between iteration and recursion c++ example "
Post a Comment