I'm learning C from K.N. King book and just arrive at a question to reverse the words in a sentence.
Here is the output:
Enter a sentence: you can cage a swallow can't you?
Reversal of sentence: you can't swallow a cage can you?
Though I've done this and it runs correctly but I want to make my code shorter. 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;
}
This can be done only with loops, arrays, getchar() and putchar() method using only <stdio.h>
header and no extra header(restrict <string.h>
header functions and methods).
Also, not use any puts() and gets() functions.
I guess this can be done only with two loops.
P.S. I am not asking any other solution, I just ask you that can I make my code shorter further.