How to reverse a string using a recursive function, without
swapping or using an extra memory?
Answer Posted / stephen
#include <iostream>
#include <string>
using namespace std;
char * reverse (char *); //function prototype
int length(char *); //function prptotype
int main()
{
int i;
char *str = new char[6], *rev = new char[6];
cin >> str;
strcpy(rev,reverse(str));
cout <<"Original "<< str << " reverse " << rev << endl;
free(str);
free(rev);
return 0;
}
int length(char *s)
{
int i;
for (i=0; *(s+i)!='\0' ; ++i);
return i;
}
char *reverse(char *s)
{
char *t;
int i, n;
n=length(s);
t = new char[n]; //opps have to add 1 here or there
wont be room for a null!
for (i=0; i<n; ++i)
{
*(t+i)=*(s+n-1-i);
}
*(t+i)='\0';
return t;
}
//can only handle words 5 letters or less.
/*based off of answer 8 i took this an intialized the
pointers so that it would run, and switched it over to the
C++ standard output commands. His algorithm was correct, he
| Is This Answer Correct ? | 8 Yes | 13 No |
Post New Answer View All Answers
Explain the difference between getch() and getche() in c?
What is the use of sizeof () in c?
What is a pointer variable in c language?
simple program of graphics and their output display
What are the advantages of Macro over function?
In C language, a variable name cannot contain?
What is a pointer and how it is initialized?
If null and 0 are equivalent as null pointer constants, which should I use?
What is auto keyword in c?
What is conio h in c?
hi... can anyone help me to make a two-dimensinal arrays in finding the sum of two elements plzzz. thnx a lot...
How will you write a code for accessing the length of an array without assigning it to another variable?
What is #include called?
How to write c functions that modify head pointer of a linked list?
How do c compilers work?