C Program to sort names in Alphabetical order

In this article, I will show you how you can write a C Program to sort names in Alphabetical order. I will explain the algorithm, concepts and then help you to write C Program to sort names in Alphabetical order.

1. Program Outline

In this program you’ll have to take two numbers as input from user and then calculate the sum and then print the average of both the numbers in terminal.

2. Concepts

To write this C program to sort names in Alphabetical order, you need to learn the following concepts of C Programming:

  1. Input
  2. Variables
  3. Loop

3. Algorithm

To write this C program, follow this Algorithm:

Step 1: First, create an array and initialize with the values.
Step 2: For loop from i=0 to i<size_of_array:
Step 3: Nest another for loop from j=0 to j<size_of_array-i-1:
Step 4: Check if(strcmp(array[j], array[j+1]) > 0):
Step 5: If yes, then swap(array[j], array[j+1])
Step 6: End nested loop.
Step 7: End external loop.
Step 8: Output sorted array

4. Program

Here’s the C Program to sort names in Alphabetical order:

#include<stdio.h>
#include<string.h>
 
main(){
   int i,j,n;
   char name[100][100],s[100];
   printf("Enter the number of names :\n");
   scanf("%d",&n);
   printf("Enter random names in any order:\n");
   for(i=0;i<n;i++){
      scanf("%s",name[i]);
   }
   for(i=0;i<n;i++){
      for(j=i+1;j<n;j++){
         if(strcmp(name[i],name[j])>0){
            strcpy(s,name[i]);
            strcpy(name[i],name[j]);
            strcpy(name[j],s);
         }
      }
   }
   printf("\nSorted names in Alphabetical order\n");
   for(i=0;i<n;i++){
      printf("%s\n",name[i]);
   }
}

5. Output

Here’s the output of the above C Program:

Default image
groot

Leave a Reply

Your email address will not be published.