-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive_palindrome_checker.cpp
More file actions
48 lines (42 loc) · 1.08 KB
/
recursive_palindrome_checker.cpp
File metadata and controls
48 lines (42 loc) · 1.08 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std;
// Returns the string that results from removing the first
// and last characters from str
char *middleCharacters(char str[], int stringLength)
{
char *middleArray = new char[(stringLength - 2)];
for (int i = 0; i < (stringLength - 2); i++)
{
middleArray[i] = str[i + 1];
}
return middleArray;
}
bool isPalindrome(char str[], int stringLength)
{
// base case #1
if (stringLength <= 1)
{
return true;
}
// recursive case
if (str[0] == str[stringLength - 1])
{
return stringLength > 2 ? isPalindrome(middleCharacters(str, stringLength), (stringLength - 2)) : true;
}
return false;
}
void checkPalindrome(char str[], int stringLength)
{
cout << "Is this word a palindrome? " << str << endl;
cout << (isPalindrome(str, stringLength) ? "TRUE" : "FALSE") << endl
<< endl;
}
int main()
{
checkPalindrome("a", 1);
checkPalindrome("motor", 5);
checkPalindrome("rotor", 5);
checkPalindrome("ercan", 5);
checkPalindrome("15951", 5);
return 0;
}