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 calloc()?
How many parameters should a function have?
c language supports bitwise operations, why a) 'c' language is system oriented b) 'c' language is problem oriented c) 'c' language is middle level language d) all the above
What is typeof in c?
Do you have any idea about the use of "auto" keyword?
Write a program in "C" to calculate the root of a quadratic equation ax^2+bx+c=0, where the value of a,b & c are known.
What is a lookup table in c?
If errno contains a nonzero number, is there an error?
how do you programme Carrier Sense Multiple Access
What is the purpose of scanf() and printf() functions?
What are the differences between new and malloc in C?
Explain what are multidimensional arrays?
How can you restore a redirected standard stream?
Can you tell me how to check whether a linked list is circular?
Explain what is meant by 'bit masking'?