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
What is gets() function?
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
What is the return type of sizeof?
What is the purpose of void pointer?
Who developed c language?
What is || operator and how does it function in a program?
What are the general description for loop statement and available loop types in c?
Why ca not I do something like this?
how do you execute a c program in unix.
What is the use of a ‘ ’ character?
How can I make sure that my program is the only one accessing a file?
What is sizeof return in c?
Write a program to swap two numbers without using third variable in c?
Write the program that calculates and prints the average of several integers. Assume that the last value read is sentinel 9999.
printf(), scanf() these are a) library functions b) userdefined functions c) system functions d) they are not functions