C program to reverse order of words in a string

Write a C program to input any string from user and reverse the order of words. How to reverse the order of words in a given string using C programming. Logic to reverse the order of words in a sentence using C program.

Example

Input

Input string : I love learning programming at Codeforwin

Output

Reversed order of words: 
Codeforwin at programming learning love I

Required knowledge

Basic C programming, If else, Loop, String

Must know -

Logic to reverse the order of words in a given string

There are many logic's to reverse the order of words. Below is the simplest approach I am using to reverse the order.

  1. Input string from user and store it in some variable say str.
  2. Declare another string to store reversed order of words, say reverse.
  3. Find a word from the end of string.
  4. Append this word to reverse.
  5. Repeat step 2-3 till the beginning of str.

Read more - Program to find reverse of a number

Program to reverse the order of words in a given string

/**
 * C program to reverse order of words in a string
 */
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[100], reverse[100];
    int len, i, index, wordStart, wordEnd;

    printf("Enter any string: ");
    gets(str);

    len   = strlen(str);
    index = 0;

    // Start checking of words from the end of string
    wordStart = len - 1;
    wordEnd   = len - 1;

    while(wordStart > 0)
    {
        // If a word is found
        if(str[wordStart] == ' ')
        {
            // Add the word to the reverse string
            i = wordStart + 1;
            while(i <= wordEnd)
            {
                reverse[index] = str[i];

                i++;
                index++;
            }
            reverse[index++] = ' ';

            wordEnd = wordStart - 1;
        }

        wordStart--;
    }

    // Finally add the last word
    for(i=0; i<=wordEnd; i++)
    {
        reverse[index] = str[i];
        index++;
    }

    // Add NULL character at the end of reverse string
    reverse[index] = '\0'; 

    printf("Original string \n%s\n\n", str);
    printf("Reverse ordered words \n%s", reverse);

    return 0;
}

Read more - Program to find reverse of an array

Output

Enter any string: I love learning programming at Codeforwin
Original string
I love learning programming at Codeforwin

Reverse ordered words
Codeforwin at programming learning love I

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>