In this tutorial you will learn about the C Program to Sort Word in String in Ascending Order and its application with practical example.
C Program to sort Word in String in Ascending Order
In this tutorial, we will learn to create a C program that will sort Word in String in Ascending Order in 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.
- String functions of c programming.
Sort Word in String in Ascending Order
As we all know the String is a collection of character data types. In strings, only one variable is declared which can store multiple values. First, we will take the input string from the user.
Then we will sort that string using the for a loop.
With the help of this program, we can sort Word in String in Ascending Order.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declare the variables for the program. 2. Take the input string from the user. 3. Pass that string to a for loop. 4. Sorting the string in ascending order. 5. Print the string. 6. End the program. |
Program to Sort Word in String in Ascending 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#include<stdio.h> #include<string.h> int main() { //declaring the variables for the program char str[100], flag; int i, j, len; //taking the input from the user printf("Enter any string: "); // reading the input gets(str); //calcuting the size of string len = strlen(str); //sorting a string 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]) { flag = str[j]; str[j] = str[j+1]; str[j+1] = flag; } } } if(str[j]>=97 && str[j]<=122) { if(str[j+1]>=97 && str[j+1]<=122) { if(str[j]>str[j+1]) { flag = str[j]; str[j] = str[j+1]; str[j+1] = flag; } } } } } //printing the output string printf("\nSame string with each word in Ascending Order:\n%s", str); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- str[100] = it will hold the string value.
- len = it will hold the integer value.
- i = it will hold the integer value.
- j = it will hold the integer value.
- flag = it will hold the string value.
Input strings from the user.
Getting the length of the string.
Sorting the string using for loop.
Printing the output.