Hello,
Though I have done this question without string functions but can anybody give me short algorithm for this. Here is the question:
Write a program that reverse the words in a sentence:
Enter a sentence: you can cage a swallow can't you?
Reversal of sentence: you can't cage a swallow can you?
Here is the Hint I've found in the book:
Use a loop to read a character one by one and store them in an array. Have the loop stop at a period, question mark, or exclamation point( the "terminating character"), which is saved in a separate char variable. Then use a second loop to search backward through the array for the beginning of the last word. Print the last word, then search backward for the next-to-last word. Repeat until the beginning of the array is reached. Finally, print the terminating character.
This program must be done without <string.h> header functions, no gets(), no puts(), only getchar() or scanf() functions.
Here is my solution:
#include <stdio.h>
#define N 100
int main(void) {
char ch[N], terminate;
int i, j, k, len;
printf("Enter a sentence: ");
for(i = 0; i < N; i++) {
ch[i] = getchar();
if(ch[i] == '?' || ch[i] == '.' || ch[i] == '!' || ch[i] == '\n') {
len = i; //Determine the length of the string
terminate = ch[i];
break;
}
}
int word_count = 0;
for(j = len - 1; j >= 0; j--) {
word_count++;
if(ch[j] == ' ') {
for(k = j+1; k < len; k++) {
printf("%c", ch[k]);
}
printf("%c", ch[j]); // print space character
len = len - word_count;
word_count = 0;
}
}
for(i = 0; i < len; i++) {
printf("%c", ch[i]);
if(ch[i] == ' ') {
break;
}
}
printf("%c", terminate);
return 0;
}