Re-arranging strings using a two dimensional array in C

The program takes a list of strings and re-arranging them into either alphabetical or reverse alphabetical order.

 
 #include <stdio.h>
 #include <string.h>
 
 void reorder(int n,char x[10][6])
 {
    char temp[10][6];
    int i,item;
 
    for(item=0;item<n-1;++item)
         for(i=item+1;i<n;++i)
             if(strcmp(&x[item][0],&x[i][0])>0)
             {
                 strcpy(&temp[0][0],&x[item][0]);
                 strcpy(&x[item][0],&x[i][0]);
                 strcpy(&x[i][0],&temp[0][0]);
             }
 }
 
 void reverse(int n,char x[10][6])
 {
     char temp[10][6];
     int i,item;
 
     for(item=0;item<n-1;++item)
          for(i=item+1;i<n;++i)
              if(strcmp(&x[item][0],&x[i][0])<0)
              {
                  strcpy(&temp[0][0],&x[item][0]);
                  strcpy(&x[item][0],&x[i][0]);
                  strcpy(&x[i][0],&temp[0][0]);
              }
 }
 
 int main()
    {
    char x[10][6];
    int i,n=0,choice;
 
    printf("Enter strings (type "end" when finished : n");
    do {
        printf("string %d : ",n);
        scanf("%s",&x[n][0]);
        printf("n%sn",&x[n][0]);
    } while(strcmp(&x[n++][0],"end"));
    printf("nEnter 1 for alphabetic, 0 for reverse alphabeticn");
    scanf("%d",&choice);
    if(choice)
        reorder(--n,x);
    else
        reverse(--n,x);
    (choice==1)?printf("nReorder") : printf("nReverse");
 
    for(i=0;i<n;i++)
        printf("nstring %d, %s",i+1,&x[i][0]);
 
    return 0;
 }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.