The objective of this exercise is to propose a new algorithm to check if a word (string without spaces) is palindrome.
- Write the function "firstlast" that takes as parameter a word (a string without spaces) and construct a new string by regrouping the characters as follows : the first and the last, the second and before the last, and so one. Example : abcdefg --> agbfced
- Notice that if the previous function is applied on a palindrome word (example: laval --> llaav), the generated string is composed of a pair of identical characters (except the last character if the original string length is odd). Write the function "isPalindrome" that verifies if a word string is palindrome, using the function "firstlast".
- Write a main program that prompts the user to enter a string and verifies if it is or not, using the previous functions.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#define size 100
void firstlast(char in[], char out[])
{
int i, j;
for(j=0;in[j];j++);
j--;
for(i=0;i<=j/2;i++)
{
out[2*i] = in[i];
out[2*i+1] = in[j-i];
}
out[j+1]='\0' ;
}
int isPalindrome(char in[])
{
char out[size];
int i;
firstlast(in,out);
printf("%s\n",out);
for(i=0;out[i];i+=2)
if(out[i+1] && out[i]!=out[i+1])
return 0;
return 1;
}
int main()
{
char in[size];
printf("Enter a word: ");
scanf("%s",in);
if(isPalindrome(in))
printf("\"%s\" is palindrome\n", in);
else
printf("\"%s\" is not palindrome\n", in);
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
UVA 1112 - Mice and Maze