I'm learning C from the K.N. King book and just arrived 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, I want to make my code shorter. I'm not asking for any other 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()
methoda using only <stdio.h>
header and no extra header (restrict <string.h>
header functions and methods). Also, no puts()
and gets()
functions. I guess this can be done only with two loops.