Monday, October 18, 2010

My little palindrome program

#include <iostream>
using namespace std;

string input()
{
    string str;
    cout << "Enter Word: ";
    cin  >> str;
    cout << endl;
    return str;
}
string upperCase(string str, int size)
{//uppercase to made comparison easy
       for (size_t i = 0; i < size; i++)
           if (islower(str[i]))
              str[i] = toupper(str[i]);
       return str;
}
bool checkPalindrome(string str, int size)
{//check first[0] and last[size-1], followed by [1] and [size-1-1], [2] and [size-1-2]
     for (size_t i = 0; i < size/2; i++)//divide by two to avoid repetition comparison
         if (str[i] != str[size-i-1])//if not equal, not palindrome
            return false;
     return true;
}

int main(void)
{
    string word=" "; char cont, counter;
    int word_size;
    do
    {
    counter = 1;
    cout << "This is a program to detect palindrome word." << endl;
    //input word
    word=input();
  
    //check length
    word_size=word.size();
    cout << "word size: " << word_size << endl;
  
    //upper case word
    string uppercased=upperCase(word,word_size);
  
    //checkpalindrome()
    cout << word << " is";
    if (checkPalindrome(uppercased,word_size))
        cout << " ";
    else
        cout << " not ";
    cout << "a Palindrome." << endl;
    //continue program?
    while (counter)
    {
          cout << "Do you want to continue?[Y/N]: ";
          cin  >> cont;
          switch (cont)
          {
           case 'Y': case 'y':
           case 'N': case 'n':
            counter=0; break;
           default:
            cout << "Wrong input.\n";
           }//switch(cont)
    }//while(counter)
  
    }while (cont=='Y'||cont=='y');//do-while(cont)
    cout << endl << "Thank you for using this program.";
    cin.get();
    cin.ignore(1000,'\n');
    return 0;
}

No comments:

Post a Comment