// to print a string in reverse order using recursion
import java.io.*;
class reverseString
{
public static void main(String args[])throws IOException
{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a String: ");
String s=br.readLine();
reverse(s, s.length());
}
public static void reverse(String S, int a)throws IOException
{
System.out.print(S.charAt(--a));
if(a>0)
reverse(S,a);
}
}
thank you so much.Can it work with loop "for(i=l;i<=0;i--)" where l is for length,then ch=charAt(i)? then print ch?
ReplyDeleteYes obviously Mr./Mrs. Anonymous, it can work the way you suggested.
DeleteBut you see we are using RECURSION here... and your suggestion uses the non-recursive solution to the problem(which in fact is much easy both for us as humans to understand and for the computer to do)
then y 2 use recursion??
DeleteIf you are very much into recursive programming, then you would know that there have always been an incentive for developing recursive solutions to problems, even when they are worse than non-recursive ones. This is just for the sake of using recursion.
DeleteNice program
ReplyDeleteIn none of these programs can I correctly find the usage of recursion.If you would like to write such a program you could have used the split function and then iterated a loop for each word that would have reduced the program complexity and it would have been done in a easier way.
ReplyDeleteThe program is just for the sake of using recursion for something that can be done using other programming logic, ahich will be better complexity wise.
DeleteBut my code here is just for the sake of recursion.
I need to tell you something..
DeleteBut before that I must make these things clear:
1. I am not trying to boast, I know that my blog is not even close to being famous or something.
2. I am not contradicting you, I agree with what you said.
3. My point is just to try and bring to your notice something that you might not be aware of.
People actually do try to find Recursive solution to print a string in reverse order. This is proven by the fact that out of all the posts I have on this blog, the most viewed one is this post only.
When learning recursion in ISC schools, they just need to show the students simple examples so that they can get the essence of recursion.
One of the favourite ways used by teachers is make them solve those problems using recursion which can be done more easily by loops.
They get to know something about the stack trace and that each call of the function has its own data set.
I guess this example of using recursion solves the purpose.
Great and I have a nifty offer: Whole House Renovation Cost Calculator split level exterior remodel
ReplyDelete