/* Filename: PalindromeCString.cpp Author: Br. David Carlson Date: December 4, 2006 This program repeatedly has the user input a string and for each checks to see if it is or is not a palindrome. It then prints the result of this test before asking the user whether to do another string. Tested with: Microsoft Visual C++ .NET 2003 g++ under Linux */ #include using namespace std; const int StringMax = 82; typedef char StringType[StringMax]; // Function prototype: bool IsPalindrome(StringType Sample); int main(void) { StringType Sample, Response; char ResponseLetter; do { cout << "Enter the string to be checked to see if it is a palindrome:" << endl; cin.getline(Sample, StringMax); if (IsPalindrome(Sample)) cout << Sample << " is a palindrome." << endl; else cout << Sample << " is NOT a palindrome." << endl; cout << "Check another string (y/n)? "; cin.getline(Response, StringMax); if (strlen(Response) > 0) // get the first letter ResponseLetter = Response[0]; else // assume that the answer is no ResponseLetter = 'n'; } while ((ResponseLetter == 'y') || (ResponseLetter == 'Y')); return 0; } /* Given: Sample A C-string of type StringType. Task: To decide if Sample holds a palindrome, a string that reads the same forwards as backwards. Return: In the function name, it returns true if Sample is a palindrome; false otherwise. */ bool IsPalindrome(StringType Sample) { int Length, MidPoint, ForwardStop, ForwardIndex, BackwardIndex; Length = strlen(Sample); if (Length < 2) // then Sample is trivially a palindrome return true; MidPoint = (Length - 1) / 2; if (2 * MidPoint + 1 == Length) // then Length is odd ForwardStop = MidPoint - 1; // Ignore the middle character. else // Length is even ForwardStop = MidPoint; BackwardIndex = Length - 1; for (ForwardIndex = 0; ForwardIndex <= ForwardStop; ForwardIndex++) { if (Sample[ForwardIndex] != Sample[BackwardIndex]) return false; BackwardIndex--; } return true; }