• Follow Us

Sort N Names in an Alphabetical Order in C

In this Searching and Sorting in C Programs, we will have a look at how to write a Program to Sort N Names in an Alphabetical Order in C Programming Language.

Sort N Names in an Alphabetical Order in C Programming Language

#include <stdio.h>
    #include <string.h>
    void main()
        char name[10][8], tname[10][8], temp[8];
        int i, j, n;
        printf("Please enter the value of n \n");
        scanf("%d", &n);
        printf("Please enter %d names n \n", n);
        for (i = 1; i <= n; i++) 
            scanf("%s", name[i]);
            strcpy(tname[i], name[i]);
        for (i = 1; i <= n - 1 ; i++)
            for (j = i + 1; j < n; j++)
                if (strcmp(name[i], name[j]) > 0) 
                    strcpy(temp, name[i]);
                    strcpy(name[i], name[j]);
                    strcpy(name[j], temp);
        printf("Input NamestSorted names\n");
        for (i = 0; i < n; i++) 
            printf("%s\t\t%s\n", tname[i], name[i]);


Please enter the value of n
Please enter 4 names

Input Names Sorted names
Bay                        Allen
Allen                     Bay
Carolin                 Carolin
Daniel                   Daniel

The program will accept some user names as input and then sort them in alphabetical order using the string operation. Create a 2D character array to store names of some fixed size. Take the names as user input using for loop.

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart