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.
> 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".
Being read-only memory, any attempt to MODIFY said string constant will immediately result in your program being killed off by the OS.
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.
09-27-2011, Texas State, San Marcos
This is a simple function that calls itself. In the process it uses
pointers to handle to the passing of the characters.
-Can only handle one name
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)
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;
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().
return; //used to return back through the function calls.
cout << *name;