In this tutorial you will learn about the C Program to sort Word in String in Descending Order and its application with practical example.
C Program to sort Word in String in Descending Order
In this tutorial, we will learn to create a C program that will sort Word in String in Descending Order using C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C Programming.
- Conditional statement in C Programming.
Sort Word in String in Descending Order:-
As we all know String is a collection of similar data type elements. In an array, only one variable is declared which can store multiple values. First will take the string input from the user. Then will pass that string to the for loop to sort it in reverse order. And at last, we will sort Word in String in Descending Order C Programming Language.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the array size from the user. 3. Taking the elements of the array. 4. Sorting the elements of the array. 5. Printing the results. 6. End program. |
Program:-
sort Word in String in Descending Order
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include<stdio.h> #include<string.h> int main() { //declaring the variable for the program char str[100], flag; int i, j, len; //display the message to take the input from the user printf("Enter any string: "); //Scanning the string input from the user gets(str); //Calculating the length of array len = strlen(str); //Sorting the string into the reverse format for(i=0; i<len; i++) { for(j=0; j<(len-1); j++) { if(str[j]<str[j+1]) { flag = str[j]; str[j] = str[j+1]; str[j+1] = flag; } } } //Printing the output string in decending order printf("\nSame string in descending order:\n%s", str); return 0; } |
Output:-
In the above program, we have first initialized the required variable
- str[100] = it will hold the elements in a string.
- flag = it will hold the number of elements in a string
- len = it will hold the integer value for the length of the string.
- i = it will hold the integer value to control the array.
- j = it will hold the integer value to control the array.
Taking input string from the user.
Checking the length of string,
Sorting the string in reverse order.
![](https://www.w3adda.com/wp-content/uploads/2021/11/4-sorting.jpg)
![](https://www.w3adda.com/wp-content/uploads/2021/11/5-printing.jpg)