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 calloc()?

623


How many parameters should a function have?

661


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

608


What is typeof in c?

601


Do you have any idea about the use of "auto" keyword?

661






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.

1718


What is a lookup table in c?

622


If errno contains a nonzero number, is there an error?

798


how do you programme Carrier Sense Multiple Access

1510


What is the purpose of scanf() and printf() functions?

719


What are the differences between new and malloc in C?

604


Explain what are multidimensional arrays?

596


How can you restore a redirected standard stream?

606


Can you tell me how to check whether a linked list is circular?

763


Explain what is meant by 'bit masking'?

639