Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program in C that will read a list of strings from stdin and identify an

ID: 3567284 • Letter: W

Question

Write a program in C that will read a list of strings from stdin and identify and generate palindromes - words spelled the same backwards and forwards.

(a) write a function ispaindrome that checks if a string is a palindrome

(b) write a function strrev with the prototype
void strrev(char *s);
which will reverse the string s in place. For example:

(c) write a function strmakepalindrome with the prototype

which will take the string s and first check to see if s is a palindrome - a word spelled the same backwards and forwards (e.g., racecar). If it is, then return the original string. If not, return a string of double length where the last half is the first string in reverse - a palindrome. For example:

and

(d) The main function will repeatedly read a line from stdin. Assume the program will be run with a redirected file, e.g., a.o < strings.txt It will then use strmakepalindrome on each input line and print the output to stdout on a new line. Assume that your character arrays will be a max of size 1024. For example, an input file:

would produce the following output:

Explanation / Answer

#include <stdio.h>
#include<string.h>
typedef int bool;
#define true 1
#define false 0

bool ispalindrome(char *s)
{
int begin, middle, end, length = 0;

while ( s[length] != '' )
length++;

end = length - 1;
middle = length/2;

for( begin = 0 ; begin < middle ; begin++ )
{
if ( s[begin] != s[end] )
{
return false;
break;
}
end--;
}
if( begin == middle )
return true;
  
  
}

void strrev(char *s)
{
int length, c;
char *begin, *end, temp;

while ( s[length] != '' )
length++;

begin = s;
end = s;

for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;

for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;

begin++;
end--;
}
}

char *strmakepalindrome(char *s)
{
if(ispalindrome(s))
return s;
  
else
{
char t[1024];
  
int i=0, j=0;
  
while(s[i] !='')
{
t[i] = s[i];
i++;
}
  
strrev(s);
  
while(s[j] !='')
{
t[i++] = s[j++];
}
  
t[i] = '';
return t;
}
}

main()
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;

fp = fopen("strings.txt", "r");

while ((read = getline(&line, &len, fp)) != -1) {

printf(" %s", strmakepalindrome(line));
}

fclose(fp);

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote