Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Reverse Every Word of the Given String


Write a C program that reverses each word in a given string.

  • Reads a sentence character by character and stores it in a string until a newline is encountered.
  • Traverses the string to find the start and end indices of each word (non-space sequences).
  • Reverses the characters within each word using a two-pointer swapping technique.
  • Displays the modified string where all words are reversed, but word order remains unchanged.
Example : pgm.c
#include <stdio.h>

int main() {
    char str[200];
    int i = 0;

    printf("Enter a sentence: ");
    while ((str[i] = getchar()) != '\n') {
        i++;
    }
    str[i] = '\0';

    int start = 0, end, temp;
    i = 0;

    while (str[i] != '\0') {
        // Find start of word
        if (str[i] != ' ') {
            start = i;
            // Find end of word
            while (str[i] != ' ' && str[i] != '\0') {
                i++;
            }
            end = i - 1;

            // Reverse the word between start and end
            while (start < end) {
                temp = str[start];
                str[start] = str[end];
                str[end] = temp;
                start++;
                end--;
            }
        } else {
            i++;
        }
    }

    printf("Reversed words: %s\n", str);

    return 0;
}

Output :

Enter a sentence: Hello World from C
Reversed words: olleH dlroW morf C