I need to make a palindrome checker with a recursive function that is of type bool and has the parameters of string to be checked and int size of the string. I have the basics down but now I need to test the first and last letter to check if it is the same or different.
In the first call to the isPalindrome() function, the first and last character of the string are compared
*If they are different, then the string is not a palindrome (base case)
*If they are the same, then the string may be a palindrome, but the rest of it must be checked (recursive
case)
*Recursively check the part of the string that excludes the first and last characters
*Each recursion shrinks the string to be checked by 2 (ignore the first and last characters)
*This process repeats until there are 0 or 1 character(s) left
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
bool isPalindrome(string, int);
int main ()
{
int string_size;
string input;
cout << "Enter a string to find out if it is a palindrome: ";
cin >> input;
string_size = input.length();
isPalindrome(input, string_size);
}
bool isPalindrome(string check, int size)
{
if ()
}
Try something out. And then ask if you need help.
The first thing you will want to do in a recursive function is write out your termination statement. So when you got to a certain point and you don’t need to check anymore. You need to return true. (Because no one broke the palindrome and you got to the end)
Next you will need an if statement to actually check the current indices. You want to check if they are not equal. If they aren’t. You can just return false.
Next you want to call the function recursively. But this time the left goes up one. And the right index goes down one
Makes sense?
int main ()
{
int string_size;
string input;
cout << "Enter a string to find out if it is a palindrome: ";
cin >> input;
string_size = input.length();
isPalindrome(input, string_size);
if (true)
{
cout << input << " is a palindrome!";
}
else
{
cout << input << " is not a palindrome!";
}
}
bool isPalindrome(string check, int size)
{
int start=0;
if ((check[size]==check[start]))
{
if ((size-start)<=1)
{
returntrue;
}
else
{
return isPalindrome(check, size-1);
}
}
else
{
returnfalse;
}
}
I looked up examples on the internet and a few of them were formatted in the way below but this also does not seem to work.
int main ()
{
int string_size;
string input;
cout << "Enter a string to find out if it is a palindrome: ";
cin >> input;
string_size = input.length();
bool output = isPalindrome(input, string_size);
if (output == true)
{
cout << input << " is a palindrome!";
}
else
{
cout << input << " is not a palindrome!";
}
return 0;
}
bool isPalindrome(string check, int size)
{
if (size<=1)
{
returntrue;
}
else
{
return (check[0] == check[size-1] && isPalindrome(check.substr(1, size-2)));
}
}