Practice Program







  • Program to arrange string characters in Dictionary order.
  • Solution:
    void main()
    {
         int i,j;
        char ch,s[20];
    
        printf("Enter the string: ");
        gets(s);
    
        printf("\nString is :");
        puts(s);
    
    
    
    
        for(i=0; s[i] != '\0'; i++)
        {
            for(j=i+1;s[j] != '\0'; j++)
            {
               if(s[i] > s[j])//checking a character at index i and j,if character
               {//at index i is greater than character at j index, then we are swapping those character.
                   ch = s[i];
                   s[i] = s[j];
                   s[j] = ch;
               }
            }
        }
    
         printf("\nString in dictionary order is : ");
         puts(s);
    }
    

    Output1
    Enter the string: DCBA

    String is :DCBA
    String in dictionary order is : ABCD

    Output2
    Enter the string: ONML

    String is :ONML
    String in dictionary order is : LMNO

    Output3
    Enter the string: SRQP

    String is :SRQP
    String in dictionary order is : PQRS









    defining a function 'to_dict' which will arrange character in dictionary order.

    void to_dict(char s[])
    {
        int i,j;
        char ch;
    
        for(i=0; s[i] != '\0'; i++)
        {
            for(j=i+1;s[j] != '\0'; j++)
            {
               if(s[i] > s[j])
               {
                   ch = s[i];
                   s[i] = s[j];
                   s[j] = ch;
               }
            }
        }
    
    }
    

    Using above define function 'to_dict()':
    void main()
    {
        char s[20] = "zyxcba";
    
        to_dict(s);
       printf("String In dictionary order is: ");
        puts(s);
    }
    

    Output1
    String In dictionary order is: abcdxyz

    Using above define function 'to_dict()':
    void main()
    {
        char s[20] = "DCBA";
    
        to_dict(s);
       printf("String In dictionary order is: ");
        puts(s);
    }
    

    Output2
    String In dictionary order is: ABCD

    Using above define function 'to_dict()':
    void main()
    {
        char s[20] = "LMNO";
    
        to_dict(s);
       printf("String In dictionary order is: ");
        puts(s);
    }
    

    Output3
    String In dictionary order is: LMNO