Word palindrome program

Our facilitator asks us to write a program that will determine if a word is a palindrome or not. It should use arrays and pointers.

Heres my code so far

const int LIMIT =5;
string word[LIMIT];

for(int i=0; i<LIMIT; i++)
{
cout<<''Enter a word";
cin>>word[i];
}

return 0;

I really dont know whats the formula for palindrome >.< help me Write your question here.

take the word and break it into character, then store those characters in an array, spell out the character backwards and see if the two words match

civic still spells civic backwards.
Another way is to compare the first char with the last, if they are the same compare the second char with the second to last char, if they are the same then continue. This is better because the function can return false as soon as failure is discovered, rather than the expense of reversing the whole string when in the worst case the first char is wrong.

To see how this is better, imagine you had to write a program that output all the palindromes in an entire dictionary. There are potentially millions of words, and most of them are not palindromes, so it is easy to see how this algorithm would execute much more efficiently.

Hope all goes well.
Can you use iterators or just pointers? I think it would be easier to use an iterator instead of a pointer.

It would look something like:

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
#include <iostream>
#include <string>

bool palindrome( const std::string &str );

int main()
{
	std::string input;
	
	while( std::getline( std::cin , input ) )
	{
		if( palindrome( input ) )
			std::cout << input << " is a palindrome." << std::endl;
		else
			std::cout << input << " is NOT a palindrome." << std::endl;
	}
	return 0;
}

bool palindrome( const std::string &str )
{
	bool isPalindrome = true;
	std::string::const_iterator left = str.cbegin() , right = str.cend()-1;
	
	for( ; left < right && isPalindrome; ++left , --right )
	{
		if( *left != *right )
			isPalindrome = false;
	}
	return isPalindrome;
}


http://ideone.com/xhYlHP
Topic archived. No new replies allowed.