Skip to content

Instantly share code, notes, and snippets.

@paranoiacblack
Created October 22, 2012 06:51
Show Gist options
  • Save paranoiacblack/3930021 to your computer and use it in GitHub Desktop.
Save paranoiacblack/3930021 to your computer and use it in GitHub Desktop.
CS 10 SI Classroom Session 4 - Palindrome Testing
#include <iostream>
using namespace std;
int main() {
// In programming, a sentinel value is a special value that guarantees
// loop termination when seen. In this example, we use 'q' to represent quit.
const string SENTINEL = "q";
string userInput = "";
cout << "Enter a string to test if it is a palindrome. Enter 'q' to quit: ";
cin >> userInput;
// We want to keep testing user inputted string to see if they are palindromes
// until they choose to quit.
while (userInput != SENTINEL) {
// Let's skip doing work if we already know it's a palindrome.
// I.E. It has one or less characters.
if (userInput.size() <= 1) {
cout << "Of course one letter or less words are palindromes!" << endl;
} else {
// Now, we actually need to figure out if the string is a palindrome.
// So, first of all, a palindrome is a word that is spelled the same
// way backwards and forwards like 'bob' or 'racecar'.
// So let's look through half of the string, and compare the front half
// to the back half.
// Let's keep a boolean variable to help us keep track of whether or
// not everything matches on the front and back.
bool isMatching = true;
for (int i = 0; i < userInput.size() / 2 && isMatching; ++i) {
// If the front half and back half at this position don't match,
// update boolean to reflect discovery.
// Note that we do `userInput.size() - i - 1` because we count from 0.
if (userInput.at(i) != userInput.at(userInput.size() - i - 1)) {
isMatching = false;
}
}
// If the loop finishes and everything matches,
// you can tell it's a palindrome.
if (isMatching) {
cout << "Cool, " << userInput << " is a palindrome!" << endl;
} else {
cout << "Hmm, it doesn't look like " << userInput << " is a palindrome!"
<< endl;
}
}
// Now, remember that we the user to enter in new input or else this will
// loop forever.
cout << "Enter a string to test if it is a palindrome. Enter 'q' to quit: ";
cin >> userInput;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment