Write a function is_palindrome() embedded in a program, that takes a pointer to
ID: 3566676 • Letter: W
Question
Write a function is_palindrome() embedded in a program, that takes a pointer to the beginning of a string and returns a boolean value. That value is true if the string is a palindrome, false otherwise. The program is supposed to get a string from the user and pass it to the function.
You can use gets() to accomplish this, or, alternatively and more secure, fgets(). A call to fgets() would look something like that:
fgets(string, 80, stdin);
Be aware though that this function includes the newline character at the end of the string, which you will want to remove.
Hand in the C program file, commented *abundantly*. (C programming, not C++ or C+)
Explanation / Answer
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 80
int is_palindrome(char []);
void clean_up(char []);
int main(void)
{
int i, n, count = 0;
char string[MAX];
printf("How many strings? ");
scanf("%d ", &n);
for (i=0;i<n;i++) {
fgets(string,MAX,stdin);
if (is_palindrome(string))
count++;
}
printf("%d ", count);
return 0;
}
// check if it is a palindrome
// return 1 if it is, 0 otherwise
int is_palindrome(char string[])
{
int i, j, len;
clean_up(string);
// printf("%s ", string);
len = strlen(string);
for (i=0,j=len-1; i<len/2;i++)
if(string[i]!=string[j--])
return 0;
return 1;
}
// remove non-letters chars in phase,
// turn upper case letters to lower case letters
void clean_up(char string[])
{
int i, j, len = strlen(string);
for (i=j=0; i<len; i++)
if (isalpha(string[i])) // check letter
string[j++] = tolower(string[i]);
string[j] = ''; // to make it a string
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.