Solution: Reverse the Words

Solution: Reverse the Words

C
#include <stdio.h>
#include <string.h>
/* Function to reverse a portion of the string */
void reverse(char *str, int start, int end) {
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char sentence[] = "C programming is fun";
int len = strlen(sentence);
/* Step 1: Reverse the entire string */
reverse(sentence, 0, len - 1);
/* Step 2: Reverse each word */
int start = 0;
for (int i = 0; i <= len; i++) {
if (sentence[i] == ' ' || sentence[i] == '\0') {
reverse(sentence, start, i - 1);
start = i + 1;
}
}
printf("%s\n", sentence);
return 0;
}