Recursion program

Pages: 12
Thank you, Shinigami. I guess I don't understand recursion as well as I thought.
My prof requested that the reverseDisplay function user a helper function so I am trying to do it this way.
???
for what purpose to use a helper function :/

you are learning recursion, are you not?
Then here are no need for helper function. Or are you learning how to use function from another function :)

And I don't know why you use &s if you don't change a given string.

Are you sure that your teachers are trained in computer programming? :D
Last edited on
Prof says:
"use helper function to pass the substring high index to the function. The helper function header is:

void reverseDisplay (const string &s, int high)

recursive function header is:

reverseDisplay(const string&s)"

This is the assigment...

well you can use a helper function and it still will be 3 line, but two functions.
If you need a helper function, here it is.

1
2
3
4
5
6
7
8
9
10
11
12
void reverseDisplay(string s)
{
	int simbol = s.length() - 1;
	reverseDisplay(s, simbol);
}

void reverseDisplay(string s, int simbol)
{
	cout << s[simbol];
	if (simbol)
		reverseDisplay(s, simbol - 1);
}


but I would use this function, one function

1
2
3
4
5
6
void reverseDisplay(string s)  //reverse display function
{
	cout << s[s.length() - 1];
	if (!s.empty())
		reverseDisplay(s.substr(0, s.length() - 1));
}
Yes, I had to change a few things in the code, but it works. I thank you... I will study this second code you sent as it looks easier.
In this two examples firs example may by a little faster if you have string over 100000 length, as it don't need to recount string length. But you can modify second example to do the same.

1
2
3
4
5
6
void reverseDisplay(string s, int simbol)  //reverse display function
{
	cout << s[simbol];
	if (simbol)
		reverseDisplay(s, simbol - 1);
}


and call it
reverseDisplay(sreverse, sreverse.length() - 1); //sends string to function for reversing
Topic archived. No new replies allowed.
Pages: 12