C Program: Employee Sorted in Alphabetical Order by Name in Structure
Question: write a program in C to read name, salary and age of n different employees as the three members of a structure named ‘employee’. Display the name, salary and corresponding age of the employees sorted on the basis of name in alphabetical order.C Source Code: Employee Record in Alphabetical Order by Name in Structure
#include<stdio.h>
#include<string.h>
/* Declaration of structure */
typedef struct
{
char name[30];
int salary;
int age;
}employee;
int main()
{
/* Declaration of array of structure */
employee e[20], temp;
int i,j,n;
printf("Enter n:\n");
scanf("%d",&n);
for(i=0;i< n;i++)
{
printf("Enter name, salary and age of employee:\n");
scanf("%s%d%d",e[i].name, &e[i].salary, &e[i].age);
}
for(i=0;i< n-1;i++)
{
for(j=i+1;j< n;j++)
{
if(strcmp(e[i].name, e[j].name) > 0)
{
temp = e[i];
e[i] = e[j];
e[j] = temp;
}
}
}
printf("Records in alphabetical order are:\n");
for(i=0;i< n;i++)
{
printf("Name: %s\n", e[i].name);
printf("Salary: %d\n", e[i].salary);
printf("Age: %d\n\n", e[i].age);
}
return 0;
}
Output
The output of the above program is:
Enter n: 3 Enter name, salary and age of employee: Ram 23000 23 Enter name, salary and age of employee: Alex 37000 32 Enter name, salary and age of employee: Alice 25000 26 Records in alphabetical order are: Name: Alex Salary: 37000 Age: 32 Name: Alice Salary: 25000 Age: 26 Name: Ram Salary: 23000 Age: 23