Here, We will learn about recursion, iteration, differences between recursion and iteration and their code in java.
Recursion
Recursion is a technique in which function calls itself until a base condition is satisfied. A recursive method solves a problem by calling a copy of itself to work on a smaller problem
Example Recursion Code in Java:
public static long fib (long n)
{
if (n <= 1)
return n;
else
return fib (n-1) + fib (n-2);
Code language: Java (java)
Iteration
Iteration is a technique in which function call repeatedly for a finite number of times. It use constructs like loops and sometime other data structures like stacks and queues to solve the problems.
Example Iteration Code in Java:
public static long fib (long n)
{
if ((n == 1) || (n == 2)){
return 1;
}
else{
long prev = 1, current = 1, next = 0;
for (long i=3; i<=n; i++){
next = prev + current;
prev = current;
current = next;
}
return next;
}
}
Code language: PHP (php)
Difference between Recursion and Iteration
Recursion | Iteration |
---|---|
Recursion uses selection structure | Iteration uses repetition structure |
It is slower than iteration due to overhead of maintaining stack | It is faster than recursion because it does not use the stack |
It uses more memory | It uses less memory. |
Infinite recursion can crash the system | Infinite looping uses CPU cycles repeatedly |
It makes code smaller | It makes code longer |
Related:
Want to Contribute:-
If you like “To The Innovation” and want to contribute, you can mail your articles to 📧 contribute@totheinnovation.com. See your articles on the main page and help other coders.😎