To ensure that a string is a palindrome, we first need to ensure that the original string and its reverse form are of the same length.
Let's suppose that the original string is sanjay and it is assigned to a string variable, str. The string is a character array, where each character is stored individually as an array element and the last element in the string array is a null character. The null character is represented as \0 and is always the last element in a string variable in C, as shown in the following diagram:
As you can see, the string uses zero-based indexing, that is, the first character is placed at index location str[0], followed by the second character at str[1], and so on. In regards to the last element, the null character is at str[6].
Using the strlen library function, we will compute the length of the entered string and assign it to the n variable. By executing the for loop in reverse order, each of the characters of the str string is accessed in reverse order, that is, from n-1 to 0, and assigned to the rev string.
Finally, a null character, \0, is added to the rev string to make it a complete string. Therefore, rev will contain the characters of the str string, but in reverse order:
Next, we will run the strcmp function. If the function returns 0, it means that the content in the str and rev strings is exactly the same, which means that str is a palindrome. If the strcmp function returns a value other than 0, it means that the two strings are not the same; hence, str is not a palindrome.
Let's use GCC to compile the palindrome.c program, as follows:
D:\CBook>gcc palindrome.c -o palindrome
Now, let's run the generated executable file, palindrome.exe, to see the output of the program:
D:\CBook>./palindrome
Enter a string: sanjay
The sanjay is not palindrome
Now, suppose that str is assigned another character string, sanas. To ensure that the word in str is a palindrome, we will again reverse the character order in the string.
So, once more, we will compute the length of str, execute a for loop in reverse order, and access and assign each character in str to rev. The null character \0 will be assigned to the last location in rev, as follows:
Finally, we will invoke the strcmp function again and supply both strings.
After compiling, let's run the program again with the new string:
D:\CBook>palindrome
Enter a string: sanas
The sanas is palindrome
Voilà! We have successfully identified whether our character strings are palindromes. Now, let's move on to the next recipe!