Sorting array elements by using Structure in C Programming
Introduction:
Sorting array elements is an essential task in programming, and it can be achieved using various techniques. One popular method of sorting arrays is by using structures in C programming. A structure in C is a user-defined data type that allows the grouping of variables of different data types under a single name. In this blog post, we will explore how to sort array elements by using structures in C programming.
#include<stdio.h>
int main()
{
struct student
{
char name[15];
int marks;
};
struct student st[5],temp;
int i,j;
/* Reading data */
for(i=0;i<5;i++)
{
printf("Enter name and marks of student\n");
scanf("%s%d",st[i].name,&st[i].marks);
}
/* Sorting */
for(i=0;i<5-1;i++)
{
for(j=i+1;j<5;j++)
{
if(st[i].marks<st[j].marks)
{
temp=st[i];
st[i]=st[j];
st[j]=temp;
}
}
}
/* Display sorted data */
printf(" \nName\tMarks\n");
for(i=0;i<5;i++)
{
printf(" %s\t%d\n",st[i].name,st[i].marks);
}
return 0;
}
Output:
Conclusion:
Sorting array elements by using structures in C programming is a powerful tool for data manipulation and analysis. It allows for the grouping of variables of different data types under a single name, making it easier to organize and manipulate data. By defining a sorting function and implementing an algorithm such as Bubble Sort, Selection Sort, or Insertion Sort, we can sort arrays of structures. With this knowledge, you can tackle a wide range of programming tasks that involve sorting arrays in C programming.
You can also Read:
No comments:
Post a Comment