Recursion help

Discussion in 'C++' started by kingo, Sep 26, 2006.

  1. kingo

    kingo New Member

    Joined:
    Aug 30, 2006
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    I need to right a recursion program to reverse a string
    the condition is
    it should be only line
    tht line code should be of returning the value
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,336
    Likes Received:
    377
    Trophy Points:
    83
    Really interesting

    Code:
    #include <iostream.h>
    #include <string.h>
    
    
    void RevStr(char *inArr, char *outArr,int start,int cLen)
    {
    	((*(outArr+start) = inArr[cLen-1]) && (cLen > 0))?RevStr(inArr, outArr, start+1, cLen-1):0;
    }
    
    
    int main()
    {
    	char * ptr = "Go4Expert";
    
    	char *outptr = 0;
    
    	outptr = new char[strlen(ptr) + 1];
    
    	RevStr(ptr, outptr, 0, strlen(ptr));
     
    	cout<<outptr;
    
    	return 0;
    }
     
  3. kingo

    kingo New Member

    Joined:
    Aug 30, 2006
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    I mean tht one line code should be of returning type.................I am not able to figure it out
     
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,336
    Likes Received:
    377
    Trophy Points:
    83
    This one line is of returning type but as the function does not need to return anything and so it does not have a return statement.

    Code:
    ((*(outArr+start) = inArr[cLen-1]) && (cLen > 0))?RevStr(inArr, outArr, start+1, cLen-1):0;
     
  5. kingo

    kingo New Member

    Joined:
    Aug 30, 2006
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
  6. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,336
    Likes Received:
    377
    Trophy Points:
    83
    My pleasure.

    Also with the return statement heres the code.
    Code:
    #include <iostream.h>
    #include <string.h>
    
    
    int RevStr(char *inArr, char *outArr,int start,int cLen)
    {
    	return(((*(outArr+start) = inArr[cLen-1]) && (cLen > 0))?RevStr(inArr, outArr, start+1, cLen-1):0);
    }
    
    
    int main()
    {
    	char * ptr = "Go4Expert";
    
    	char *outptr = 0;
    
    	outptr = new char[strlen(ptr) + 1];
    
    	RevStr(ptr, outptr, 0, strlen(ptr));
     
    	cout<<outptr;
    
    	return 0;
    }
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice