Skip to main content

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

 

Sort strings in the dictionary order

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

int main() {
   char str[5][50], temp[50];
   printf("Enter 5 words: ");

   // Getting strings input
   for (int i = 0; i < 5; ++i) {
      fgets(str[i], sizeof(str[i]), stdin);
   }

   // storing strings in the lexicographical order
   for (int i = 0; i < 5; ++i) {
      for (int j = i + 1; j < 5; ++j) {

         // swapping strings if they are not in the lexicographical order
         if (strcmp(str[i], str[j]) > 0) {
            strcpy(temp, str[i]);
            strcpy(str[i], str[j]);
            strcpy(str[j], temp);
         }
      }
   }

   printf("\nIn the lexicographical order: \n");
   for (int i = 0; i < 5; ++i) {
      fputs(str[i], stdout);
   }
   return 0;
}

Output

Enter 5 words: R programming
JavaScript
Java
C programming
C++ programming

In the lexicographical order:
C programming
C++ programming
Java
JavaScript
R programming

Comments

Popular posts from this blog

C Program to Calculate Difference Between Two Time Periods

  Calculate Difference Between Two Time Periods # include <stdio.h> struct TIME { int seconds; int minutes; int hours; }; void differenceBetweenTimePeriod (struct TIME t1, struct TIME t2, struct TIME *diff) ; int main () { struct TIME startTime , stopTime , diff ; printf ( "Enter the start time. \n" ); printf ( "Enter hours, minutes and seconds: " ); scanf ( "%d %d %d" , &startTime.hours, &startTime.minutes, &startTime.seconds); printf ( "Enter the stop time. \n" ); printf ( "Enter hours, minutes and seconds: " ); scanf ( "%d %d %d" , &stopTime.hours, &stopTime.minutes, &stopTime.seconds); // Difference between start and stop time differenceBetweenTimePeriod(startTime, stopTime, &diff); printf ( "\nTime Difference: %d:%d:%d - ...

C Program to Display its own Source Code as Output

  C program to display its own source code # include <stdio.h> int main () { FILE *fp; int c;     // open the current input file fp = fopen(__FILE__, "r" ); do { c = getc(fp); // read character putchar (c); // display character } while (c != EOF); // loop until the end of file is reached   fclose(fp); return 0 ; }

HTML TABLE CODE

<! DOCTYPE   html > < html   lang = "en" > < head >     < meta   charset = "UTF-8" >     < meta   http-equiv = "X-UA-Compatible"   content = "IE=edge" >     < meta   name = "viewport"   content = "width=device-width, initial-scale=1.0" >     < title >this is form</ title >     < script >          function   checkdetail () {              var  x  =  document.frm.n.value;              if  (x  ==   null   ||  x  ==   " "   ||  x.length  >   15   ||  x.length  <   3 ) {         ...