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
pgm to find any error in linklist(in single linklist check whether any node points any of previous nodes instead of next node)
Why pointers are used?
what is reason of your company position's in india no. 1.
If you know then define #pragma?
How to get string length of given string in c?
Explain what would happen to x in this expression: x += 15; (assuming the value of x is 5)
What is the difference between a free-standing and a hosted environment?
how to count no of words,characters,lines in a paragraph.
Why we not create function inside function.
a c variable cannot start with a) an alphabet b) a number c) a special symbol d) both b and c above
Can you please explain the scope of static variables?
What functions are in conio h?
What does it mean when a pointer is used in an if statement?
write a c program for swapping two strings using pointer
write a C program:There is a mobile keypad with numbers 0-9 and alphabets on it. Take input 0f 7 keys and then form a word from the alphabets present on the keys.