Write C program that will accept sentence from user and reverse individual word of it.

SOLUTION.

#include <'stdio.h'>
#include <'string.h'>
#include <'ctype.h'>

// Function to reverse a word
void reverseWord(char *start, char *end) {
    while (start < end) {
        char temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }
}

// Function to reverse individual words in a sentence
void reverseWords(char *str) {
    char *wordStart = NULL;
    char *temp = str;

    while (*temp) {
        if (wordStart == NULL && !isspace(*temp)) {
            wordStart = temp; // Mark start of the word
        }
        
        if (wordStart && (isspace(*temp) || *(temp + 1) == '\0')) {
            reverseWord(wordStart, (isspace(*temp) ? temp - 1 : temp));
            wordStart = NULL; // Reset for next word
        }
        temp++;
    }
}

int main() {
    char str[100];
    
    // Input sentence from user
    printf("Enter a sentence: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = 0; // Remove newline character if present
    
    // Reverse words
    reverseWords(str);
    
    // Display the result
    printf("Reversed words: %s\n", str);
    
    return 0;
}
    

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.