C program to sort names in alphabetical order using structures


Structure is a collection of different datatype variables, grouped together under a single name.

Features of structure

The features of structure in the C programming language are as follows −

  • It is possible to copy the contents of all the structure elements of different datatypes to another structure variable of its type by using an assignment operator.

  • For handling the complex datatypes, it is better to create structure within another structure, which is called nested structures.

  • It is possible to pass an entire structure, individual elements of structure and an address of structure to a function.

  • It is possible to create structure pointers.

Declaration and initialization of structures.

General form of structure declaration is as follows −

datatype member1;
   struct tagname{
      datatype member2;
      datatype member n;
};

Here,

  • struct is the keyword.
  • tagname specifies name of structure.
  • member1, member2 are the data items.

For example,

struct book{
   int pages;
   char author [30];
   float price;
};

Program

Following is the C program to sort the names in an alphabetical order by using the structures

 Live Demo

#include<stdio.h>
#include<string.h>
struct tag{
   char name[10];
   int rno;
};
typedef struct tag node;
node s[5];
sort(int no){
   int i,j;
   node temp;
   for(i=0;i<no-1;i++)
   for(j=i+1;j<no;j++)
   if(strcmp(s[i].name,s[j].name)>0){
      temp=s[i];
      s[i]=s[j];
      s[j]=temp;
   }
}
void main(){
   int no,i;
   fflush(stdin);
   printf("Enter The Number Of Students:");
   scanf("%d",&no);
   for(i=0;i<no;i++){
      printf("Enter The Name:");
      fflush(stdin);
      gets(s[i].name);
      printf("Enter the Roll:");
      scanf("%d",&s[i].rno);
   }
   sort(no);
   for(i=0;i<no;i++){
      printf("%s\t",s[i].name);
      printf("%d
"
,s[i].rno);    } }

Output

When the above program is executed, it produces the following result −

Enter The Number of Students:5
Enter The Name:Priya
Enter the Roll:3
Enter The Name:Hari
Enter the Roll:5
Enter The Name:Pinky
Enter the Roll:7
Enter The Name:Lucky
Enter the Roll:1
Enter The Name:Krishna
Enter the Roll:2
Hari 5
Krishna 2
Lucky 1
Pinky 7
Priya 3

Updated on: 02-Sep-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements