C Program: Employee Sorted in Descending Order by Age 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 age in descending order.C Source Code: Employee Record in Descending Order by Age in Structure
#include<stdio.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(e[i].age< e[j].age)
{
temp = e[i];
e[i] = e[j];
e[j] = temp;
}
}
}
printf("Sorted records 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: 4↲ Enter name, salary and age of employee: Ram↲ 10000↲ 58↲ Enter name, roll and marks of student: Shyam↲ 11000↲ 67↲ Enter name, roll and marks of student: Hari↲ 12000↲ 37↲ Enter name, roll and marks of student: Prakash↲ 13000↲ 48↲ Sorted records are: Name: Shyam Salary: 11000 Age: 67 Name: Ram Salary: 10000 Age: 58 Name: Prakash Salary: 13000 Age: 48 Name: Hari Salary: 12000 Age: 37