Sorting strings alphabetically using C

Source Code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void reorder(int n, char *x[]);
int main(){
    int i , no_string;
    char *x[10];
    printf("Enter the no of strings: ");
    scanf("%d",&no_string);
    printf("Enter the strings: \n");
    for(i = 0; i < no_string; i++){
        x[i] = (char*) malloc (12*sizeof(char));
        printf("string %d: ",i+1);
        scanf("%s", x[i]);
    }
    printf("The sorted strings are: ");
    reorder(i,x);
    for(i = 0; i < no_string; i++){
        printf("\nstring %d: %s", i+1, x[i]);
    }
    return 0;
}
void reorder(int n, char *x[]){
    char *temp;
    int i,item;
    for(item = 0; item < n-1; ++item){
        for(i = item+1; i < n; ++i){
            if(strcmp(x[item],x[i]) > 0){
                temp = x[item];
                x[item] = x[i];
                x[i] = temp;
            }
        }
    }
    return;
}

Output

 

 

string_sort

SHARE Sorting strings alphabetically using C

You may also like...

1 Response

  1. Hello ! I have some questions on this program. Why should I type scanf("%s", x[i]) instead of scanf("%s", &x[i]) ? Is that related to pointer declaration?

Leave a Reply

Your email address will not be published.

Share