In this tutorial you will learn about the C Program to Sort Names in Alphabetical Order and its application with practical example.
C Program to Sort Names in Alphabetical Order
In this tutorial, we will learn to create a C program that will Sort Names in Alphabetical 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.
- String functions in C programming.
- Conditional statement in C Programming.
Sort Names in Alphabetical 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 alphabetical order. And at last, we will Sort Names in Alphabetical 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 list of the names. 4. Sorting the list of the names. 5. Printing the results. 6. End program. |
Program:-
Sort Names 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 31 32 33 34 |
#include<stdio.h> #include<string.h> int main() { //declaring the variable for the the program int i,j,n; char str[100][100],s[100]; //Taking input number of names printf("Enter number of names :\n"); scanf("%d",&n); //Taking the names in input printf("Enter names in any order:\n"); for(i=0;i<n;i++){ scanf("%s",str[i]); } //Comparing the string and sorting the string for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(strcmp(str[i],str[j])>0){ strcpy(s,str[i]); strcpy(str[i],str[j]); strcpy(str[j],s); } } } //Printing the sorted names printf("\nThe sorted order of names are:\n"); for(i=0;i<n;i++){ printf("%s\n",str[i]); } return 0; } |
Output:-
In the above program, we have first initialized the required variable
- s[100] = it will hold the elements in a string.
- str[100][100] = it will hold the string value.
- i = it will hold the integer value to control the array.
- j = it will hold the integer value to control the array.
- n = it will hold the integer value to control the array.
Taking input string from the user.
Sorting the string in alphabetical order.