75 views

What is the functionality of above function Do ( ) ?
a. Check whether string is odd palindrome
b. Check whether the string is even palindrome
c.  Check whether the string is palindrome
d.  None of the above

retagged | 75 views

Edit:

The correct answer would be D) none.

The reason is $gate1$ and $gate$ both point to the first character. So loop condition $gate1 < gate$ is already false and hence the loop breaks and the function returns 1.

The original answer was option C) by assuming (erroneously) that the while loop condition is $gate1 < gate2$, whereas the condition is $gate1 < gate$
edited
how???

Edit:  The following discussion assumes wrong loop condition. So the code in the question actually always returns 1.

gate1 points to the first character of the string (base address of the string) and gate2 points to the last element.

The following part compares the current characters, being pointed by gate1 and gate2, if they're not equal straightaway return 0 (i.e., not a palindrome).

while(gate1 < gate2){
if(*gate1++ != *gate2--)
return 0;
}

*gate1++ : this means first increment gate1, but since it is post increment, first dereference the pointer, then increment it to point the next character.

*gate2-- : this means first decrement gate2, but since it is post decrement, first dereference the pointer, then decrement it to point the previous character.

So the "if" condition first compares the current character, if they match, changes the corresponding pointers to point to their corresponding next elements.

If the whole loop ran without returning 0 (i.e.till the middle of the string) then return 1. So it checks if the string is palindrome or not.

thanks :)

Edit:  The following discussion assumes wrong loop condition. So the code in the question actually always returns 1.

@Gabbar: It doesn't need to. Whatever middle element be, the string will be a palindrome if the string by removing the middle element is a palindrome.

Consider $aba$, gate1 points at first $a$, gate2 points at last $a$

First Run:

Loop condition: $gate1 < gate2$ satisfied

Inside loop: $if$ condition satisfied. Increment gate1 and decrement gate2. Now both point at b.

Second Run:

Loop condition: $fails$, so exit out of loop and return 1.

Point to note is whatever the middle element be (one character long), the string $a\_a$ (consider the underscore a wildcard for single character)  will always be a palindrome.

oops !

thanks