Home / Programs / C Program to Sort Elements in Lexicographical Order (Dictionary Order)
🚀 Programming Example

C Program to Sort Elements in Lexicographical Order (Dictionary Order)

👁 4,215 Views
💻 Practical Program
📘 Step Learning
This program sorts the 10 strings (entered by the user) in lexicographical order (dictionary order).

💻 Program Code

#include<stdio.h>
#include <string.h>

int main()
{
    int i, j;
    char str[10][50], temp[50];

    printf("Enter 10 words:\n");

    for(i=0; i<10; ++i)
        scanf("%s[^\n]",str[i]);


    for(i=0; i<9; ++i)
        for(j=i+1; j<10 ; ++j)
        {
            if(strcmp(str[i], str[j])>0)
            {
                strcpy(temp, str[i]);
                strcpy(str[i], str[j]);
                strcpy(str[j], temp);
            }
        }

    printf("\nIn lexicographical order: \n");
    for(i=0; i<10; ++i)
    {
        puts(str[i]);
    }

    return 0;
}
                        

🖥 Program Output

Enter 10 words:
C
C++
Java
PHP
Python
Perl
Ruby
R
JavaScript
PHP

In lexicographical order: 
C
C++
Java
JavaScript
PHP
PHP
Perl
Python
R
Ruby
                            

📘 Explanation

To solve this program, a two-dimensional string str is created.

This string can hold maximum of 10 strings and each string can have maximum of 50 characters (including null character).

To compare two strings, strcmp() function is used. Also, we used strcpy() function to copy string to a temporary string temp.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.