Recursion

C

case.learning

Hi everyone,

I'm a C++ novice. I'm trying to learn recursion and have written this
piece of code but it doesn't work. Could you help me to see where it
goes wrong? Thanks.

bool PalindromeHelper(string s)
{
int len = s.length();
if (len == 1 || len == 0)
return true;
else
return (s[0] == s[len-1]) &&
PalindromeHelper(s.substr(1, len-2));
}
 
O

osmium

I'm a C++ novice. I'm trying to learn recursion and have written this
piece of code but it doesn't work. Could you help me to see where it
goes wrong? Thanks.

bool PalindromeHelper(string s)
{
int len = s.length();
if (len == 1 || len == 0)
return true;
else
return (s[0] == s[len-1]) &&
PalindromeHelper(s.substr(1, len-2));
}

If the first char is not equal to the last char you sould return
immediately. Once false, alwasy false.
 
C

case.learning

I'm a C++ novice. I'm trying to learn recursion and have written this
piece of code but it doesn't work. Could you help me to see where it
goes wrong? Thanks.
bool PalindromeHelper(string s)
{
int len = s.length();
if (len == 1 || len == 0)
return true;
else
return (s[0] == s[len-1]) &&
PalindromeHelper(s.substr(1, len-2));
}

If the first char is not equal to the last char you sould return
immediately. Once false, alwasy false.

Thanks, but this piece of code that you quoted here actually worked.
The other one didn't work though.

Mark.
 
M

Markus Schoder

I'm a C++ novice. I'm trying to learn recursion and have written this
piece of code but it doesn't work. Could you help me to see where it
goes wrong? Thanks.

bool PalindromeHelper(string s)
{
int len = s.length();
if (len == 1 || len == 0)
return true;
else
return (s[0] == s[len-1]) &&
PalindromeHelper(s.substr(1, len-2)); }

If the first char is not equal to the last char you sould return
immediately. Once false, alwasy false.

It does thanks to the short circuit behaviour of &&.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,785
Messages
2,569,624
Members
45,318
Latest member
LuisWestma

Latest Threads

Top