In: Computer Science
Write an interactive C program that asks a user to enter a sentence from the keyboard, and prints the sentence with all the words spelled backwards.
Note: you may assume that each sentence will have at most 50 characters and each word is separated by a space.
Sample code execution: bold information entered by user
enter a sentence: hello ece 175 class
olleh ece 571 ssalc
continue (q to quit)? y
enter a sentence: May the force be with you
yaM eht ecrof eb htiw uoy
continue (q to quit)? a
enter a sentence: The quick brown fox jumps over a lazy dog
ehT kciuq nworb xof spmuj revo a yzal god
continue (q to quit)? d
enter a sentence: No lemon, no melon
oN ,nomel on nolem
continue (q to quit)? q
Below is the solution:
#include <stdio.h>
#include <string.h>
void reverse_string(char*);
void reverse_words(char*);
int main() {
int len;
while (1)
{//reading the data from console until we enter q to quit
printf("Enter a sentence: ");
char a[100];
fgets(a,sizeof(a),stdin);
len= strlen (a);
if (len>0 && a[len-1]=='\n')
a[--len]= '\0';
reverse_words(a);//reverses the words
printf("%s\n", a);
printf("continue (q to quit)?");
char quit[10];//takes the input if to quit
fgets(quit,sizeof(quit),stdin);
len= strlen (quit);
if (len>0 && quit[len-1]=='\n')
quit[--len]= '\0';
if (strcmp(quit,"q")==0){//if the entered char is q, then break the
loop
break;
}
}
return 0;
}
//in this we split each word and pass it to reverse_strings to
reverse each word
void reverse_words(char *s) {
char b[100], *t, *z;
int c = 0;
t = s;
while(*t) { //processing complete string
while(*t != ' ' && *t != '\0') { //extracting word from
string
b[c] = *t;
t++;
c++;
}
b[c] = '\0';
c = 0;
reverse_string(b); // reverse the extracted word
z = b;
while (*z) { //copying the reversed word into original
string
*s = *z;
z++;
s++;
}
while (*s == ' ') { // skipping space(s)
s++;
}
t = s; // pointing to next word
}
}
/*
* Function to reverse a word.
*/
void reverse_string(char *t) {
int l, c;
char *e, s;
l = strlen(t);
e = t + l - 1;
for (c = 0; c < l/2; c++) {
s = *t;
*t = *e;
*e = s;
t++;
e--;
}
}