I am exploring working with strings and I have some questions about this particular program. Could someone help explain why and how the x < i/2
as well as the word[i - 1 - x]
works.
Why does it have to be i/2
?
Why does it have to be word[i - 1 - x]
?
#include <stdio.h>
int main()
{
char word[15];
int i, x;
printf("Enter a word\n");
scanf("%s", word);
for(i = 0; word[i] != '\0';)
i = i + 1;
for(x = 0; x< i/2; x++)
if(word[x] != word[i-1-x])
{printf("Your word is not a palindrome\n");}
else
{
printf("Your word is a palindrome\n");
}
}
Why does it have to be
i/2
?
It does not have to be this way: i
would work too, but it would not be optimal. If you have checked all character pairs going at it from both ends, and the letters are the same up to the middle of the word, the rest of the checks will succeed as well.
Consider for example the word "alula"
. You start by comparing the initial a
to the last a
, then you compare l
in the second position to l
in the second position from the back, then you compare u
to itself. Now you've reached the middle of the word at i/2
. If you continue, you would compare the same pairs of characters, but you would pick them from different indexes. It is guaranteed that all these pairs are going to match, so you can save yourself some CPU cycles by skipping them altogether.
Why does it have to be
word[i - 1 - x]
?
Because arrays are zero-based. i-1
is the index of the last character, hence i - 1 - x
is the x
-th index counting from the back.