C program to sort element in lexicographic order or dictionary order.

C program to sort element in lexicographic order or dictionary order. In this program we use strings and it’s function (method) that is..

  • strcmp() function (this function is use to compared two string)
  • strcpy() function (this function is use to copy one string into other)
  • loop
  • gets (use to take input from user)
  • puts (use to print output)

above function and loop are use in this program. So now we write program to sort element in lexicographic order or dictionary order and take a look of output.

SOURCE CODE:


#include<stdio.h>
#include<string.h>
int main(){
    int i,j,p[20];
    char a[5][20];
    printf("enter 5 word to get dictionary order of the word:\n");
    for(i=0;i<5;i++){
        gets(a[i]);
    }
    for(i=0;i<5;i++){
        for(j=i+1;j<5;j++){
            if(strcmp(a[i],a[j])>0){
                strcpy(p,a[i]);
                strcpy(a[i],a[j]);
                strcpy(a[j],p);
            }
        }
    }
    printf("words are in dictionary order :\n");
    for(i=0;i<5;i++){
        puts(a[i]);
    }
    return 0;
}

OUTPUT:

enter 5 word to get dictionary order of the word:
array
loop
string
function
c language
words are in dictionary order :
array
c language
function
loop
string

ANOTHER OUTPUT:

enter 5 word to get dictionary order of the word:
PYTHON
C LANGUAGE
JAVA
HTML
CSS
words are in dictionary order :
C LANGUAGE
CSS
HTML
JAVA
PYTHON

DETAIL EXPLANATION:

strcmp() : strcmp function basically use to compare two string but remember one thing strcmp return integer value syntax of string comparison function is

// strcmp(first string , second string);

Remember if

string 1 > string 2 then strcmp function return positive value that is 1

string 1< string 2 then strcmp function return negative value that is -1

string 1 = string 2 then strcmp function return 0

strcpy() : strcpy function copy one string into other string and syntax of string copy function is

// strcpy(first string , second string);

Some more practical here for your practice 

c practical





0 Comments