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
Can you explain the four storage classes in C?
What are the types of data files?
What is the size of array float a(10)?
How to write a program for machine which is connected with server for that server automatically wants to catch the time for user of that machine?
Combinations of fibanocci prime series
Do pointers need to be initialized?
Explain how can you check to see whether a symbol is defined?
What is pointer & why it is used?
Do you have any idea about the use of "auto" keyword?
Study the following C program :call_me (myvar)int myvar;{ myvar +- 5; }main(){int myvar;myvar = 3;call_me(myvar);printf("%d ",myvar);What will be printed a) 3 b) 5 c) 8 d) symbol
What is difference between structure and union in c programming?
How will you declare an array of three function pointers where each function receives two ints and returns a float?
What is the use of #include in c?
How can I read and write comma-delimited text?
What is an arrays?