What are the benefits of recursion over simple loops Can rec
What are the benefits of recursion over simple loops? Can recursions be used to find specific words, find and replace these words? Would you use a loop or recursion for this?
Solution
Ans)
What are the benefits of recursion over simple loops? Can recursions be used to find specific words, find and replace these words? Would you use a loop or recursion for this?
Benifits of Recursion:
-A method calls itself to solve a apecific program is called recursion.
-A recursion is mostly useful in cases such as tree traversal algorithms and binary search algorithms.
-A recursion uses the stack memory to complete its task.When a method is called the controller moves to the wherethe method is defind and perform its task.
-The main advantage of the recursion is it reduces the time complexity of the program.
-A recursive program is easier to visualize.
-In programs such as devide and conquer approach recursive method is best approach and reduces the problem size at every step and also takes a less time like in problems such as binary search trees.
-Simple and fast to code. Less effort and will be easily understood by others
Yes, recursions can be used to find the specific words and replace those words.For example replace() method and replaceAll() methods are some of the examples of recursive replace of specific words.
import java.io.*;
public class RecursiveReplace {
public static void main(String args[]) {
String Str = new String(\"This is an example to replace words using recursion\");
System.out.print();
System.out.println(\"Final String is :\" +Str.replace(\"example\", \"Task\"));
}
}
This replace method internally performs the recursive operation.
I would always prefer to use a recursion for this type of operations because it is easy to use and implement.If we use a loop for this type of operations preformance will be reduced. So, recursion is more preferable.
