[try Beta version]
Not logged in

 
palindrome recursive

Mar 4, 2018 at 3:47pm
I need to write a program for a palindrome using recursive functions and this is what I got so far but the problem is that my code only works if its a word not a sentence, what can I do?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
using namespace std;

bool Test(string sentence,int first,int last);
bool Test(string sentence,int first,int last)
{

if (last<=1)
return true;
else
if (sentence[first]==sentence[last-1])
return Test(sentence,first+1,last-1);

else return false;
}

int main()
{
string sentance;
getline (cin, sentance);
int last=sentance.length();

Test(sentance,0,last);
if (Test(sentance,0,last))
cout<<"It is a Palindrome"<<endl;
else
cout<<"It is not a palindrome"<<endl;
return 0;
}
Last edited on Mar 4, 2018 at 4:03pm
Mar 4, 2018 at 4:26pm
first, indent your code.
¿how do you define a palindrome for a sentence? If you want to ignore whitespace and punctuation, the I suggest to create another string where you will copy only the valid characters.
by the way, ¿why do you Test() twice?
Mar 4, 2018 at 7:51pm
like ne555 said you need to indent your code in order to make it more viable for you to see your mistakes
Mar 4, 2018 at 7:53pm
so you could declare a string to be able to let you type a sentence.
Mar 5, 2018 at 12:07am
I think something like this should work, if you really need to recurse:
1
2
3
4
5
bool const Test(char const *chars, int len) {
    return len <= 1 ||
        chars[0] == chars[len - 1] &&
        Test(chars + 1, len - 1);
}


Then call it like this (or make a little wrapper function as I did here):

1
2
3
bool const TestStringForPalindrome(string const &s) {
    return Test(s.c_str(), s.size());
}
Last edited on Mar 5, 2018 at 12:48am
Topic archived. No new replies allowed.