Deitel & Deitel, C How to Program 6th Edition, Exercise 6.31 (Palindromes)
/*6.31 (Palindromes) A palindrome is a string that is spelled the same way forward and backward.
Some examples of palindromes are: “radar,” “able was i ere i saw elba,” and, if you ignore blanks, “a
man a plan a canal panama.” Write a recursive function testPalindrome that returns 1 if the string
stored in the array is a palindrome and 0 otherwise. The function should ignore spaces and punctuation
in the string.*/
#include <stdio.h>
#include <string.h>
int testPalindrome(char arr[]);
int main() {
char sentence[51];
int result;
gets(sentence);
result = testPalindrome(sentence);
result == 1 ? printf("It is Palindrome\n"): printf("It is not Palindrome\n");
return 0;
}
int testPalindrome(char arr[]) {
int i, j = 0, last;
char letters[50];
for (i = 0; i < 50; i++ )
if (arr[i] == arr[51]) {
last = i - 1;
break;
}
for (i = 0; i <= last; i++)
if ((arr[i] > 'A' && arr[i] < 'Z') || (arr[i] > 'a' && arr[i] < 'z')) {
letters[j] = arr[i];
j++;
}
last = --j;
for (i = 0; i < last; i++) {
if (letters[i] != letters[j])
return 0;
j--;
}
return 1;
}
Some examples of palindromes are: “radar,” “able was i ere i saw elba,” and, if you ignore blanks, “a
man a plan a canal panama.” Write a recursive function testPalindrome that returns 1 if the string
stored in the array is a palindrome and 0 otherwise. The function should ignore spaces and punctuation
in the string.*/
#include <stdio.h>
#include <string.h>
int testPalindrome(char arr[]);
int main() {
char sentence[51];
int result;
gets(sentence);
result = testPalindrome(sentence);
result == 1 ? printf("It is Palindrome\n"): printf("It is not Palindrome\n");
return 0;
}
int testPalindrome(char arr[]) {
int i, j = 0, last;
char letters[50];
for (i = 0; i < 50; i++ )
if (arr[i] == arr[51]) {
last = i - 1;
break;
}
for (i = 0; i <= last; i++)
if ((arr[i] > 'A' && arr[i] < 'Z') || (arr[i] > 'a' && arr[i] < 'z')) {
letters[j] = arr[i];
j++;
}
last = --j;
for (i = 0; i < last; i++) {
if (letters[i] != letters[j])
return 0;
j--;
}
return 1;
}
Let me know in the comments if this page helped you somehow.
It is nice to know if my work helped someone, thanks :)
Comments
Post a Comment