recursive function to reverse a word

I need to make a recursive function that will output a word in reverse order ie input : hello, output : olleh

heres what i have so so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void ReverseText (string word, int startIndex, int lastIndex)

int _tmain(int argc, _TCHAR* argv[])
{
      int word;
      cout << "Enter a word: " << endl;
      cin >> word;
      return 0;
}
void ReverseText (string word, int startIndex, int lastIndex)
{



}


I don't know what to put into the ReverseText function
Can anyone help with this?
Last edited on
I did this program and can't find it and I'm working on my final but the concept is this: Make a char array with a const int as the size (say 300) and make sure they only enter 299 or less chars.

Then use a for loop in your reverseText function and pass in your char array and thennn:

length = strlen(charArray)

for (int i = length; i >= 0; i--) //<---Reads the array backwards. You can also read the last char into a temp array first, and swap positions but this is SO much easier.
{
cout << charArray[i];
}

You may have to use a pointer in there. I can't find the program it's off the top of my head.

Also in your main(), you wouldn't want to declare word as an int. A word isn't an int, its an array of chars or a string.
Last edited on
rageoutfool wrote:
Also in your main(), you wouldn't want to declare word as
an int. A word isn't an int, its an array of chars or a string.

Correct. I just want to add that I'd prefer a string over a
char array, because I don't want to worry about size limits.

The loop suggestion is also a good one (that's how I would do it
too if there were no implementation constraints), however, the
assignment specifically asks to reverse the string using recursion.

I have a question.

What do startIndex and lastIndex represent?
What is ReverseText("WORLD", 1, 2) supposed
to be? "OWRLD"? "WROLD"? Something else?

Assuming that startIndex and lastIndex indicate the part of the string
that you want to reverse, I would do something that would work like this:

string ReverseTextFromTo(string word, int firstIndex, int lastIndex)
{
  first, split word into three parts,
  w1 (from the beginning of word to firstIndex),
  w2 (from firstIndex to lastIndex),
  w3 (from lastIndex to the end of word)

  then, return w1 + ReverseText(w2) + w3
}

ReverseText("") = ""

ReverseText("abcd") = 
ReverseText("bcd") + 'a' = 
(ReverseText("cd") + 'b') + 'a' =
... = 
"" + 'd' + 'c' + 'b' + 'a' = 
"dcba"

A couple of things I believe you'll find useful:

http://cplusplus.com/reference/string/string/length/
http://cplusplus.com/reference/string/string/substr/
Last edited on
Topic archived. No new replies allowed.