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];
for (i=0; i<n; ++i)
{
*(t+i)=*(s+n-1-i);
}
*(t+i)='\0';

return t;
}

/*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
just forgot to setup the memory*/

Is This Answer Correct ?    10 Yes 14 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is gets() function?

679


If one class contains another class as a member, in what order are the two class constructors called a) Constructor for the member class is called first b) Constructor for the member class is called second c) Only one of the constructors is called d) all of the above

629


What is the return type of sizeof?

603


What is the purpose of void pointer?

609


Who developed c language?

646






What is || operator and how does it function in a program?

639


What are the general description for loop statement and available loop types in c?

695


Why ca not I do something like this?

597


how do you execute a c program in unix.

648


What is the use of a ‘’ character?

595


How can I make sure that my program is the only one accessing a file?

691


What is sizeof return in c?

627


Write a program to swap two numbers without using third variable in c?

626


Write the program that calculates and prints the average of several integers. Assume that the last value read is sentinel 9999.

3139


printf(), scanf() these are a) library functions b) userdefined functions c) system functions d) they are not functions

646