divya
divya

Reputation: 11

how recursion works in this C # program?

using System; 

class RevStr { 

  public void displayRev(string str) { 
    if(str.Length > 0)  
      displayRev(str.Substring(1, str.Length-1)); 
    else  
      return; 

    Console.Write(str[0]); 
  } 
} 

class MainClass { 
  public static void Main() {   
    string s = "this is a test"; 
    RevStr rsOb = new RevStr(); 

    Console.WriteLine("Original string: " + s); 

    Console.Write("Reversed string: "); 
    rsOb.displayRev(s); 

    Console.WriteLine(); 

} }

Upvotes: 1

Views: 320

Answers (4)

McArthey
McArthey

Reputation: 1646

Maybe the easiest way to think of recursion is as a Stack. In fact, if you search for Stack and recursion you'll see many ways to implement recursion using a Stack.
In your code you are effectively stripping the first character and then pushing the remainder onto the stack. When the condition is met that it needs to "pop" the stack it executes your Console.Write() statement for each element on the stack. In your case it means that it is going to print the first character of the string that was pushed onto the stack. Remember that a Stack is handled in LIFO (Last In, First Out) order so this results in handling the strings in reverse order.

See if this link helps: The Animation of Recursion, Simple String Reversal

Upvotes: 0

Andre Gross
Andre Gross

Reputation: 263

it´s throwing an exception.

example:

displayRev("bla");
displayRev("la");
displayRev("a");
//Now it gets an error
//The string.Length "a" is bigger than 0 (it´s 1)
//in displayRev(str.Substring(1, str.Length-1)); he wants to make a SubString beginning at the
//index 1 (the Second character), but the string contains only 1 character 

//if-Statement have to look like:

if(str.Length > 1)  
      displayRev(str.Substring(1, str.Length-1)); 
    else  
      return; 

Upvotes: 1

Jesus Ramos
Jesus Ramos

Reputation: 23268

Since the recursive call is first as long as the string has contents it will recursively call itself with one less character. Once it's all out of characters the calls unwind printing one character at a time. It prints backwards because if you take the call stack (for a smaller string)

displayRev("test")
displayRev("est")
displayRev("st")
displayRev("t")
displayRev("") // unwinds here

So if you look at the first letter of each and write it down it becomes, tset, the reverse of test.

Upvotes: 2

Petar Minchev
Petar Minchev

Reputation: 47373

This is a recursive method that prints a string reversed. To print a string str reversed, first print str without the first character reversed(recursive step) and then print the first character.

For example to print abcd reversed, print bcd reversed which is dcb and then print a(the first character).

Upvotes: 1

Related Questions