Hi,
Can somebody write a sample code to reverse a string using recursion.
Basically a function which takes string as input parameter, reverses the string using recusrion and returns back the reversed string to calling function.

Thank you
Naveen

Post what you have put up tilll now and we will definately help you out.

I have written this code:

#include <stdio.h>
void rev_str(char* s)
{
 
    if(*s != '\0')
         rev_str(s+1);
 
    
 printf("%c",*s);
}
 
int main()
{
   rev_str("born2c0de");
   return 0;
}

Here i am able to reverse the string and print it out...but i want rev_str function to return the reversed string or ideally reverse the passed string itself.

Can you help me out?

Edited 6 Years Ago by peter_budo: Adding code tags

Pass in another string which will be loaded with the reversed string as you go through your return side of the function

#include<conio.h>
char* reverse(char *s,int start,int last){
	char temp;
	if(start>=last){
	return s;
	}else{
	temp = s[start];
	s[start]=s[last];
	s[last]=temp;
	reverse(s,start+1,last-1);
	}
}
main(){
char *s="visha";
clrscr();
s = reverse(s,0,strlen(s)-1);
printf("\n ====> %s lenght : %d ",s,strlen(s));
}

Edited 6 Years Ago by Nick Evan: Added code-tags

Comments
Answering homework questions 4 years late is totally useless. Read the Rules and help on this site!

Leaving aside the 3+ year grave digging...

> char *s="visha";
This MAY be in read-only memory. It certainly is for most modern compilers on most modern operating systems. But since you seem to be using crusty old Turbo C (why I don't know), it will "work for you".

> s[start]=s[last];
Being read-only memory, any attempt to MODIFY said string constant will immediately result in your program being killed off by the OS.

> reverse(s,start+1,last-1);
Your if part returns a result, but this doesn't.
The result will be that the function will return random garbage to the caller (for any non-trivial string). Again, you may be getting lucky. Others who try this code will fare less well.

Here's a better version of gfhgh's code:

#include <stdio.h>
#include <string.h>

void reverse(char **s, int start, int last)
{
	char tmp;
	if (start >= last)
		return;
	char *s2 = *s;
	tmp = s2[start];
	s2[start] = s2[last];
	s2[last] = tmp;
	reverse(s, start + 1, last - 1);
}

int main()
{
	char *s = strdup("Hello World");
	printf("%s\n", s);
	reverse(&s, 0, strlen(s) - 1);
	printf("%s\n", s);
}

Here is another version:

You could also pass the array to the function instead of making it global.

char arr[100] = "madam";

int reverse(int start, int last)
{
	
	if (arr[start] != arr[last])
		return 0;	

	if (start >= last)
		return 1;
	
	else 
		return reverse(start + 1, last - 1);
	
}

#include

void rev(char *l, char *r);


int main(int argc, char *argv[])
{
char buf[] = "the world will go on forever";
char *end, *x, *y;

// Reverse the whole sentence first..
for(end=buf; *end; end++);
rev(buf,end-1);


// Now swap each word within sentence...
x = buf-1;
y = buf;

while(x++ < end)
{
if(*x == '\0' || *x == ' ')
{
rev(y,x-1);
y = x+1;
}
}

// Now print the final string....
printf("%s\n",buf);

return(0);
}

void reverse (int index char *str ) ;

int main (void)

{

char name[100];

printf ( Enter a mutli-word string ) ;

gets(name) ;

reverse (strlen(name) name ) ;

}

void reverse (int index char *str )

{

if (--index < 0 )

{

return ;

}

else

{

putchar ( *(str + index) ) ;

reverse (index str) ;

}

}

/*                          


                            Zachary T
                            09-27-2011, Texas State, San Marcos

                                        File: reverse_function.cpp

  ___________________________________________________________________________________

                This is a simple function that calls itself. In the process it uses
                pointers to handle to the passing of the characters. 

                Errors***
                -Can only handle one name

  ___________________________________________________________________________________

*/

#include <cstdlib>
#include <iostream>
using namespace std;

//prototype for the reverse function
void reverse(char *name);
//const variable for the size of the array
const int NAME_SIZE = 60;


int main(int argc, char *argv[])
{
    char answer;
    while (answer != 'n' && answer != 'N')
    {
    //If you dont use cin, and you create your own char arrays, then spaces wont end the reverse() function.
    //EX:  char name[] = "What ever you want to be reversed...";

    char name[NAME_SIZE];//Char array to hold the name from the cin call.

    cout << "Enter the name to be reversed(no spaces):";
    cin >> name;


    reverse(name);//Call to the reverse(), passing the name as an argument, because arrays are pointers.
    cout << endl;

    cout << "Run again?";
    cin >> answer;
    }

    return 0;
}


/*
    reverse()
             This function uses an if statement to check the first char on the array
             Then it calls itself and passes the next element in the array as an argument
             This will continue untill the end of the array, then it will return out, and
             cout letter as it returns at the end.
*/
void reverse(char *name) 
{ 
  if(*name)//checks to see if there is a char that the address points to.
  {  
    reverse(name+1);//takes the next step array, and jumps into next call of reverse().
  } 
  else
  { 
    return; //used to return back through the function calls.
  }

  cout << *name; 
}

Edited 4 Years Ago by masterplanner: had to

Comments
A year too late, and in the wrong language.

Hi..this is a simple code in C to reverse an input string

#include<stdio.h>
#include<conio.h>
void rev();
main()
{

     printf("Enter the input string:");
     rev();
     printf(" is the reversed string");
     getch();
}
void rev()
{
     char a=getchar();
     if(a=='\n')
                return;
     else
     {
         rev();
         printf("%c",a);
     }
}
//Function that reverses a given number


int reverse(int num)
{
static int sum,base =1;
sum=0;

if(num>0)
{
reverse(num/10);
sum += (num%10)*base;
base*=10;
} 
return sum;


}
Comments
Please read the thread before responding. The topic is reversing a *string*.
This article has been dead for over six months. Start a new discussion instead.