Thursday, 1 August 2013

Recursion-Reversing a String(JAVA)

public class Reverse
{
String s;
static String r="";
 
 public Reverse()
{
}
public void reverse(String s,int i)//earlier we tried using only string as an argument in that case i would be either static or class variable and in both case for all the stack elements value if i would be 5 hence output will "yyyyy"
{

if(i==5)
{
r=r+s.charAt(i);
return;

}
reverse(s,i+1);
r=r+s.charAt(i);//everything that comes after the function call is call in the reverse method we have used that concept
}
public static void main (String args[])
{
Reverse obj=new Reverse();
obj.reverse("Tanmay",0);
System.out.println(obj.r);
}
}

No comments:

Post a Comment