Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Ch14_8 Palindrome testing
- //Rawlin Stone
- //*make a recursive function that will take a 3 parameter argument list
- //*First parameter will be the string name, 2nd parameter is the starting
- // index of the string, and the 3rd parameter will be the last index of the string
- //*This function will check whether the string is a palindrome or not
- //*The return type of the function will be boolean type.
- //It will return true if the string is palindrome, otherwise return false.
- /*****
- A palindrome is a string such as "madam", "radar", "dad", and "I" that reads the same forwards and backwards.
- The empty string is regarded as a palindrome. Write a recursive function bool isPalindrome(string str, int lower, int upper)
- that returns true IFF the string str in positions lower through upper (inclusive at both ends) is a palindrome.
- Test your function by writing a main function that repeatedly asks the user to enter strings terminated by the ENTER key.
- These strings are then tested for palindromicity. The program terminates when the user presses
- the ENTER key without typing any character before it.
- ****/
- #include <iostream>
- #include <cstring>
- //need it for strlen
- #include <cctype>
- using namespace std;
- //prototype
- bool isPalindrome(char[], int, int);
- int main()
- {
- //there aren't any palindromes larger than tattarrattat, but there are phrases. 64 should be enough.
- //initialize the size to 64.
- const int SIZE=64;
- char inputStr[SIZE];
- do{
- //output to the user
- cout << "Please input a word to be verified whether or not it is a palindrome: " << endl;
- cin.getline(inputStr, SIZE);
- if (inputStr[0] == NULL)
- {
- return 0;
- }
- int beginning = 0;
- //use strlen to find the total size of the string, then -1 because
- //the last term is a null operator \0
- int ending = strlen(inputStr) -1;
- //a variable to store the value of
- bool returned;
- //call the isPalindrome function
- returned = isPalindrome(inputStr, beginning, ending);
- //if returned is true
- if (returned == true)
- cout << inputStr << " is a palindrome. "<<endl;
- else
- cout << inputStr << " isn't a palindrome. "<<endl;
- }while (strlen(inputStr) != NULL);
- return 0;
- }
- /*************************************
- isPalindrome
- This function is a recursive function.
- It will search through the cstring
- inputStr to check that it matches
- at all positions forward and back.
- ***************************************/
- bool isPalindrome(char inputStr[], int b, int e)
- {
- if (inputStr[b] == ' ') b++;
- if (inputStr[e] == ' ') e--;
- //if you only put 1 letter i
- if (b >= e)
- return true;
- //if the first and last characters don't match then it's not a palindrome
- if (inputStr[b] != inputStr[e])
- return false;
- //recursive call
- return isPalindrome(inputStr, b + 1,e - 1);
- }
Advertisement
Add Comment
Please, Sign In to add comment