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

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top