C programming A palindrome is a word that reads the same forward as it does back
ID: 3761525 • Letter: C
Question
C programming
A palindrome is a word that reads the same forward as it does backward. An example of a valid palindrome is the word “racecar”. An example of a word that is not a palindrome is “trust” (it reads backwards as “tsurt”). Develop a C program that identies palindrome words. Your program should:
• Read words to be checked from a le called input.txt (You can nd this le on the course website).
• If a word is a palindrome it prints it to a le named palindromes.txt
I can use strings and arrays,if comments could be added to de code, would be great so i can follow and understand it.
I hope someone can help me, thank you.
The input FILE contains this words:
chool
aibohphobia
lists
alula
bake
cammac
civic
read
deified
late
absent
Explanation / Answer
/**C program that reads as input.txt file and reads words from the file. Then finds the palindrome words and write those palindrome words
to a new text file "palindromes.txt" file */
//palindromes.c
#include<stdio.h>
#include<cstdlib>
#include<conio.h>
#include<string.h>
//function prototype
bool isPalindrome(char word[]);
int main()
{
//character string
char word[100];
char fileName[50]="input.txt";
//open a file input.txt
FILE *fp=fopen(fileName,"r");
//check file exists or not
if(!fp)
{
printf("File doesnot exist.");
getch();
exit(0);
}
//open a output file "palindromes.txt"
FILE *fwrite=fopen("palindromes.txt","w");
//write palidrome words to file
while(fscanf(fp,"%s",word)!=EOF)
{
//check for palindromes
if(isPalindrome(word))
fprintf(fwrite, "%s ",word);
}
//close the file objects
fclose(fp);
fclose(fwrite);
printf("enter key to close");
getch();
return 0;
}
//Returns true if the word is palindrome otherwise returen false
bool isPalindrome(char word[])
{
char rev[100];
//copy the char string to re
strcpy(rev,word);
//reverse string
strrev(rev);
//compare two string
return strcmp(word,rev)==0;
}
--------------------------------------------------------------------------------
Sample input.txt
chool
aibohphobia
lists
alula
bake
cammac
civic
read
deified
late
absent
---------------------------------------------------------------------------------------
Sample output palindromes.txt
aibohphobia
alula
cammac
civic
deified
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.