C program to sort each word from a given string in descending order

In this article, we will learn about how to sort or arrange each word from any given string (by the user at run-time) in descending order.

In this program, each word is sorted character-wise. For example, if the given string by the user is "this is fresherearth," Here we have a total of three words ("this," "is," and "fresherearth") present inside the string. Therefore, after sorting each word, the string will become "tsih si srrokeedccca."

In this way, the following program will sort each and every word from the given string in descending order (alphabetical-wise).

#include<stdio.h>
#include<conio.h>
int main()
{
    char str[100], chTemp;
    int i, j, len;
    printf("Enter any string: ");
    gets(str);
    len = strlen(str);
    for(i=0; i<len; i++)
    {
        for(j=0; j<(len-1); j++)
        {
            if(str[j]>=65 && str[j]<=90)
            {
                if(str[j+1]>=65 && str[j+1]<=90)
                {
                    if(str[j]<str[j+1])
                    {
                        chTemp = str[j];
                        str[j] = str[j+1];
                        str[j+1] = chTemp;
                    }
                }
            }
            if(str[j]>=97 && str[j]<=122)
            {
                if(str[j+1]>=97 && str[j+1]<=122)
                {
                    if(str[j]<str[j+1])
                    {
                        chTemp = str[j];
                        str[j] = str[j+1];
                        str[j+1] = chTemp;
                    }
                }
            }
        }
    }
    printf("\nSame string with each word in descending order:\n%s", str);
    getch();
    return 0;
}

The program was written in the Code::Blocks IDE; therefore, after a successful build and run, here is its sample run:

c sort each word in descending order

Now supply any string, say "how are you," and press the ENTER key to see the same string with its words sorted in descending order:

sort each word in descending order c

Here is a list of some of the main steps used in the above program:

C Quiz


« Previous Program Next Program »