Difference between Loop and Recursion

Loop statement and Recursion both are programming practices that helps in reducing repetitive code and keeps the code clean and structured.

Loop statements are used to loop or iterate through a code block until a condition is met. Recursion is implemented using a function and a recursive function is one that calls itself until a condition is met. Thus, it is very important to have an exit condition in both the cases otherwise they turn out to be never ending. In recursion, the exit condition is often termed as Base Case.

In below example, all the number less than 10 are printed by using FOR Loop as well as Recursion.

Using For Loop
.....
.....
for(int i=0; i System.out.println("Printing..." + i ); //This print statement will be printed until i < 10
}
//do something here
.....
.....

Using Recursion

......
......
printFunc(i) {
if(i < 10) {
System.out.println("Printing..." + i );
printFunc(i+1); //printFunc is calling itself and it will call itself till i < 10. Thus, i < 10 is a Base Case here.
}
else {
//do something here
.....
.....
}
}

It is always possible to translate from recursion to loop and vice versa.

Hope you find this information useful. Please leave your footprints in comments section below for any queries or suggestions…!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">