In this tutorial you will learn about the C Program to Sort a String in Alphabetical Order and its application with practical example.
C Program to Sort a String in Alphabetical Order
In this tutorial, we will learn to create a C program that will Sort a String in Alphabetical 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.
- Concepts of for loop.
- Using String functions of c language.
Sort a String in Alphabetical 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 will take the string from the user. Then will check the number of elements of the string. Now we will arrange that string in alphabetical order.
With the help of this program, we can Sort a String in Alphabetical Order
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Add a sting to the variable 3. Print the given string. 4. Now pass thatstring to for loop for sorting 5. Printing the result string. 6. End |
Program to Sort a String in Alphabetical 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 |
#include <stdio.h> #include <string.h> //including header files in the program int main () { //declaring variables required for the program char string[] = "w3adda"; char flag; int i, j; //calculating string size int n = strlen(string); //sting before sorting printf("String before sorting - %s \n", string); //for loop for sorting for (i = 0; i < n-1; i++) { for (j = i+1; j < n; j++) { if (string[i] > string[j]) { flag = string[i]; string[i] = string[j]; string[j] = flag; } } } //printing output in alpfabetical order printf("String after sorting - %s \n", string); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- string1[] = it will hold the string value.
- flag = it will hold the temporary value.
- i = it will hold the integer value for the loop.
- j = it will hold the integer value for the loop.
- n = it will hold the size of the string.
Including the required header files.
Taking Input string.
Printing before the alphabetical order.
Printing a String in Alphabetical Order.
Program Code for arranging.