
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Names in Alphabetical Order using C String Functions
Problem
Sort the names given by the user at runtime in an alphabetical order by using the bubble sort technique.
Solution
The logic used to print the names in alphabetical order is as follows −
for (i=1; i < ITEMS; i++){ for (j=1; j <= ITEMS-i ; j++){ if (strcmp (string[j-1], string[j]) > 0){ /* Exchange of contents */ strcpy (dummy, string[j-1]); strcpy (string[j-1], string[j]); strcpy (string[j], dummy ); } } }
Example
Following is the C program to sort the names in an alphabetical order by using the string functions −
#define ITEMS 5 #define MAXCHAR 20 main( ){ char string[ITEMS][MAXCHAR], dummy[MAXCHAR]; int i = 0, j = 0; /* Reading the list */ printf ("Enter names of %d items
",ITEMS); while (i < ITEMS) scanf ("%s", string[i++]); /* Sorting begins */ for (i=1; i < ITEMS; i++){ for (j=1; j <= ITEMS-i ; j++){ if (strcmp (string[j-1], string[j]) > 0){ /* Exchange of contents */ strcpy (dummy, string[j-1]); strcpy (string[j-1], string[j]); strcpy (string[j], dummy ); } } } printf ("
Alphabetical list
"); for (i=0; i < ITEMS ; i++) printf ("%s
", string[i]); }
Output
When the above program is executed, it produces the following output −
Enter names of 5 items computers architecture organization microprocessor networking Alphabetical list architecture computers microprocessor networking organization
Advertisements