I have to write a palindrome test function, I'm thinking of creating two arrays. One is inserted by the user which then populates the second array in reverse.
Is this the right direction to go?
Thx
I have to write a palindrome test function, I'm thinking of creating two arrays. One is inserted by the user which then populates the second array in reverse.
Is this the right direction to go?
Thx
u will get the result by that approach also. But I would suggest u to compare the characters at the first half withe second character by character.
You can do that or you can do what dkalita suggested.
To expand on his suggestion :
Say the input is "1001".
To check if it is a palindrome you need to compare the first value + n, to the last value - n.
Lets start :
// Input
<input > value = 10001 .
The first value is 1, and the last value is 1, the second value is 0 and
the second-last value is 0. Then the first value index is the same as
the second value index, so its a palindrome. Look at the table below:
n firstValue lastValue "1 0 0 0 1 "
------------------------------------------------
0 1 1
1 0 0
2 0 0
Hope you see how that works. Now lets put this into an algorithm :
string input = "";
cin >> input;
cout << isPalindrome(input); //define below
So what should it look like ? Well remember the example at the beginning of this post. Lets try to convert that into an algorithm.
bool isPalindrome(string str){
//we need to check the first + n and last - n and compare it so :
int last= str.size() - 1; //the - 1 is there because str.size() returns 1 plus the end
//if first equals last then we are pointing in the same index so
// that means it passed the last below
for(int n= 0; n < last - n; n++ ){
//compare each character, first + n != last - n , where first is element 0.
if( str[ n] != str[ last - n] ) return false;
}
return true;
}
So that doesn't matter if the string entered is an even or odd length?
So that doesn't matter if the string entered is an even or odd length?
Nope it does not matter. The check n != last makes it so. But just though about it, the check in the for loop should be :
for(int n = 0; n < last - n; ++n);
So I made that change.
We are not checking any value after the first + n and the last - n
reaches the same index or after the first reaches an index greater than first.
Try to make your own the first way you though about it. Then look
back at this example after you get that working. That way you
will understand it better.
look at this and see if it helps. Its a table for the "for loop"
<input> = 1001
//we check the first + n against the last - n element
//when n is 0 in our for loop
first last
1 1
//when n is 1 in our loop
first last
0 0
//now after that our first + n is greater than last - n so we stop.