C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Sort array of strings

C Program: Sort array of strings

C

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[100][100], temp[100];

    int n, i, j;

 

    // Input number of strings

    printf("Enter number of strings: ");

    scanf("%d", &n);

    getchar(); // To consume the newline after scanf

 

    // Input strings

    printf("Enter %d strings:\n", n);

    for (i = 0; i < n; i++) {

        fgets(str[i], sizeof(str[i]), stdin);

        str[i][strcspn(str[i], "\n")] = '\0'; // remove newline

    }

 

    // Sort strings (bubble sort)

    for (i = 0; i < n - 1; i++) {

        for (j = i + 1; j < n; j++) {

            if (strcmp(str[i], str[j]) > 0) {

                strcpy(temp, str[i]);

                strcpy(str[i], str[j]);

                strcpy(str[j], temp);

            }

        }

    }

 

    // Display sorted strings

    printf("\nStrings in alphabetical order:\n");

    for (i = 0; i < n; i++) {

        printf("%s\n", str[i]);

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter number of strings: 4
Enter 4 strings:
banana
apple
cherry
mango

Strings in alphabetical order:
apple
banana
cherry
mango

Explanation

  • strcmp() compares two strings lexicographically (dictionary order).
  • strcpy() swaps them if they are out of order.
  • The outer and inner loops ensure all strings are compared and sorted — similar to bubble sort.